简体   繁体   English

Ruby TCPSocket通信

[英]Ruby TCPSocket communication

I am learning TCPSocket and have a simple server written: 我正在学习TCPSocket并编写了一个简单的服务器:

require 'socket'

server = TCPServer.open(2000)

loop {
  client = server.accept
  p client.gets
  client.print("bar")
  client.close
}

and simple client written: 和简单的客户写道:

require 'socket'

hostname = 'localhost'
port = 2000
socket = TCPSocket.open(hostname, port)

socket.print("foo")
p socket.gets

When I run these in separate terminals with either the server or client communicating one way (ie one "prints" and the other "gets") I get the expected string on the other side. 当我在单独的终端中运行这些程序时,服务器或客户端以一种方式进行通信(即,一个“打印”而另一个“获取”),则在另一端得到了预期的字符串。 When I run these as written, with the client first "print"-ing a message to the server and then the server "gets"ing it to then "print" a string to the client, it just hangs. 当我以书面形式运行它们时,客户端首先“打印”-向服务器发送一条消息,然后服务器“获取”它然后再“打印”字符串给客户端,它只是挂了。 What is causing this issue? 是什么导致此问题?

Your program does following: 您的程序执行以下操作:

The connection is established between client and server. 在客户端和服务器之间建立连接。

Client side 客户端

  • Calls print("foo") - exactly 3 bytes are transmitted to the server. 调用print(“ foo”)-恰好3个字节传输到服务器。
  • Calls gets - waits for data from server but server never send any. 呼叫获取-等待来自服务器的数据,但服务器从不发送任何数据。

Server side 服务器端

  • Calls gets - The ruby function gets parse stream data and it always return the whole line. 调用gets-ruby函数获取解析流数据,并且始终返回整行。 But the server received only "foo" and the it has no idea whether it is whole line or not. 但是服务器仅收到“ foo”,并且服务器不知道它是否是整行。 So it is waiting forever for new line character which client never send. 因此,它将永远等待客户端从未发送过的换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM