Scala相当于python echo服务器/客户端示例? [英] Scala equivalent of python echo server/client example?
本文介绍了Scala相当于python echo服务器/客户端示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
scala中所有服务器示例都使用actor,reactor等...
All the "server" example in scala use actors, reactors etc...
有人可以教我如何编写一个死掉的简单echo服务器和客户端吗?例如服务器和客户端:
Can someone show me how to write a dead simple echo server and client, just like the following python example of Server and Client:
# 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
推荐答案
您可以在标准库中执行以下操作:
You can do following within standard library:
// 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
If you don't mind using extra libraries, you might like Finagle.
这篇关于Scala相当于python echo服务器/客户端示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文