ruby tcpsocket


===== server

require 'socket'
server = TCPServer.new("0.0.0.0", 2000)

clients = []

Thread.new do
  loop {
    client = server.accept
    puts '--find client'
    clients.push client
    puts '--clients client'
  }
end

loop {
  puts "client-size:#{clients.size}"
  clients.each do |client|
    begin
      str = client.recvfrom(1024)
      puts str
      client.puts('this message from server')
    rescue Exception => myException
      puts "Exception rescued : #{myException}"
      clients.delete(client)
    end
  end
  sleep 1
}
client.close
======= client
require 'socket'

host = '127.0.0.1'
port = 2000
msg="client1: sync_data"
s = TCPSocket.open(host, port)
s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
loop  do
  s.puts(msg)
  resp = s.gets
  puts "resp:#{resp}"
  sleep 1
end

阅读更多

没有更多推荐了,返回首页