scala中的所有“服务器”示例使用演员,反应堆等…
有人可以告诉我如何写一个死的简单回声服务器和客户端,就像下面的Server和Client的python示例一样:
# A simple echo server import socket host = '' port = 50000 backlog = 5 size = 1024 s = socket.socket(socket.AF_INET,socket.soCK_STREAM) s.bind((host,port)) s.listen(backlog) while 1: client,address = s.accept() data = client.recv(size) if data: client.send(data) client.close()
# A simple echo client import socket host = 'localhost' port = 50000 size = 1024 s = socket.socket(socket.AF_INET,socket.soCK_STREAM) s.connect((host,port)) s.send('Hello,world') data = s.recv(size) s.close() print 'Received:',data
解决方法
您可以在标准库中执行以下操作:
// Simple server import java.net._ import java.io._ import scala.io._ val server = new ServerSocket(9999) while (true) { val s = server.accept() val in = new BufferedSource(s.getInputStream()).getLines() val out = new PrintStream(s.getoutputStream()) out.println(in.next()) out.flush() s.close() }
// Simple client import java.net._ import java.io._ import scala.io._ val s = new Socket(InetAddress.getByName("localhost"),9999) lazy val in = new BufferedSource(s.getInputStream()).getLines() val out = new PrintStream(s.getoutputStream()) out.println("Hello,world") out.flush() println("Received: " + in.next()) s.close()
如果您不介意使用额外的图书馆,您可能会喜欢Finagle.