在gets()中从Ruby中损坏的TCP套接字恢复

前端之家收集整理的这篇文章主要介绍了在gets()中从Ruby中损坏的TCP套接字恢复前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在读取TCP套接字上的输入行,类似于: @H_403_2@class Bla def getcmd @sock.gets unless @sock.closed? end def start srv = TCPServer.new(5000) @sock = srv.accept while ! @sock.closed? ans = getcmd end end end

如果端点在getline()运行时终止连接,则gets()挂起.

我该如何解决这个问题?是否有必要进行非阻塞或定时I / O?

解决方法

您可以使用select来查看是否可以安全地从套接获取,请参阅以下使用此技术实现TCPServer. @H_403_2@require 'socket' host,port = 'localhost',7000 TCPServer.open(host,port) do |server| while client = server.accept readfds = true got = nil begin readfds,writefds,exceptfds = select([client],nil,0.1) p :r => readfds,:w => writefds,:e => exceptfds if readfds got = client.gets p got end end while got end end

这里是一个试图打破服务器的客户端:

@H_403_2@require 'socket' host,7000 TCPSocket.open(host,port) do |socket| socket.puts "Hey there" socket.write 'he' socket.flush socket.close end

猜你在找的Ruby相关文章