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

阅读更多
个人分类: Ruby/Rails
上一篇Postgres 备忘录
下一篇Install ChromeDriver
想对作者说点什么? 我来说一句

TCPSocket编程

2013年07月16日 16KB 下载

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

关闭
关闭