Scala 相当于 python echo 服务器/客户端示例?
scala 中的所有“服务器”示例都使用 actor、reactor 等...
有人可以告诉我如何编写一个简单的 echo 服务器和客户端,就像下面的 服务器 和 客户端:
# 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
All the "server" example in scala use actors, reactors etc...
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在标准库中执行以下操作:
如果您不介意使用额外的库,您可能会喜欢 骗术。
You can do following within standard library:
If you don't mind using extra libraries, you might like Finagle.
我刚刚写了一篇关于使用 Akka IO 和 Iteratees 创建一个简单的基于命令的套接字服务器的博客文章。
也许这可能会引起兴趣。
http://leon.radley.se/2012/08/ akka-command-based-socket-server/
I just wrote a blog post about using Akka IO and Iteratees to create a simple command based socket server.
Maybe it could be of interest.
http://leon.radley.se/2012/08/akka-command-based-socket-server/
您必须使用 Java 套接字。我在以下位置找到了 Scala Socket 服务器/客户端的一个很好的示例: http://www.scala-lang .org/node/55
You would have to use Java Sockets. I found a nice example of a Scala Socket Server/Client at: http://www.scala-lang.org/node/55
您可以使用 netty java 库。以下是 Scala 中的用法示例:
https://github.com/mcroydon/scala-echo-server
一般需要使用Java Socket API。在这个示例中使用了Java Socket API,但是整个服务器被包装在 Actor 中,以便在单独的线程中处理客户端,而不是阻塞接受器线程(与您通常在 Java 中执行的操作相同,但您将直接使用线程)。
You can use netty java library. Here is an example usage in Scala:
https://github.com/mcroydon/scala-echo-server
Generally you need to use Java Socket API. In this example Java Socket API are used, but the whole server is wrapped in Actor in order to process clients in separate thread and not to block acceptor thread (the same thing you will normally do in Java, but you will use threads directly).
Josh Suereth 最近发布了一个使用 scalaz Iteratees 的 NIO echo 服务器示例。需要 scalaz 库
Josh Suereth recently posted an example of an NIO echo server using scalaz Iteratees. Requires the scalaz library