创建server
创建client
require 'socket'
include Socket::Constants
socket = Socket.new(AF_INET, SOCK_STREAM, 0)
sockaddr = Socket.sockaddr_in(9999, 'localhost')
socket.bind(sockaddr)
socket.listen(5)
begin
while 1 do
client_socket, client_sockaddr = socket.accept_nonblock
puts "The command is #{client_socket.readline.chomp}"
flag = rand(10)
result = flag % 2 == 0 ? '\{\"status\" = \"false\"\}' : '\{\"status\" = \"true\"\}'
end
rescue Errno::EAGAIN, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR
IO.select([socket])
retry
end
创建client
require 'socket'
client = TCPSocket.open('localhost', '9999')
client.send("oracle\n", 0) # 0 means standard packet
client.close
本文介绍了一个简易的TCP服务器和客户端的实现过程。服务器监听本地9999端口,接收并打印客户端发送的命令,并随机返回状态信息。客户端连接服务器并发送一条命令后关闭连接。
32

被折叠的 条评论
为什么被折叠?



