如何显示通过套接字接收到的字符?

发布于 2024-09-25 03:50:41 字数 473 浏览 4 评论 0原文

我有一个非常简单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

为你拒绝所有暧昧 2024-10-02 03:50:41

问题是您的代码仅在每次有人连接时运行一次 while 循环(TCPServer#accept 接受连接)。尝试更多类似的东西:

require 'socket'  

puts "Simple Echo Server V1.0"  
server = TCPServer.new('127.0.0.1', '2150')

socket = server.accept  

while line = socket.readline
  socket.puts line
  puts line
end

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:

require 'socket'  

puts "Simple Echo Server V1.0"  
server = TCPServer.new('127.0.0.1', '2150')

socket = server.accept  

while line = socket.readline
  socket.puts line
  puts line
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文