如何显示通过套接字接收到的字符?
我有一个非常简单的 Ruby 程序,充当“回显服务器”。当您通过 telnet 连接到它时,您输入的任何文本都会回显。那部分正在工作。如果我添加“putc”语句来在运行程序的控制台上打印每个接收到的字符,则仅打印显示的第一个字符。之后,它继续将信息回显给 telnet 客户端,但控制台上没有打印任何内容。
以下是一个显示该问题的小型精简程序。
我对 Ruby 非常陌生,可能犯了一个典型的菜鸟错误。我做错了什么?
require 'socket'
puts "Simple Echo Server V1.0"
server = TCPServer.new('127.0.0.1', '2150')
cbuf = ""
while socket = server.accept
cbuf = socket.readchar
socket.putc cbuf
putc cbuf
end
I have a very simple Ruby program that acts as an "echo server". When you connect to it via telnet any text you type is echoed back. That part is working. If I add a 'putc' statement to also print each received character on the console running the program only the very first character displayed is printed. After that it continues to echo things back to the telnet client but there is nothing printed on the console.
The following is a small, stripped down program that exhibits the problem.
I am very new to Ruby and have probably made a typical rookie mistake. What did I do wrong?
require 'socket'
puts "Simple Echo Server V1.0"
server = TCPServer.new('127.0.0.1', '2150')
cbuf = ""
while socket = server.accept
cbuf = socket.readchar
socket.putc cbuf
putc cbuf
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您的代码仅在每次有人连接时运行一次 while 循环(TCPServer#accept 接受连接)。尝试更多类似的东西:
The problem is that your code is only running the while loop once for every time somebody connects (TCPServer#accept accepts a connection). Try something more like: