在Ruby中,可以使用socket
庫進行TCP/IP通信
require 'socket'
# 創建一個TCP套接字
client_socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM)
# 連接到服務器
server_address = Socket.ip_address_list("0.0.0.0").detect{|intf| !intf.ipv6_private?}
server_port = 12345
client_socket.connect(server_address, server_port)
# 向服務器發送數據
message = "Hello, Server!"
client_socket.write(message)
# 接收服務器的響應
response = client_socket.read(1024)
puts "Server response: #{response}"
# 關閉套接字
client_socket.close
require 'socket'
# 創建一個TCP套接字
server_socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM)
# 綁定地址和端口
server_address = Socket.ip_address_list("0.0.0.0").detect{|intf| !intf.ipv6_private?}
server_port = 12345
server_socket.bind(server_address, server_port)
# 開始監聽連接
server_socket.listen(1)
puts "Server is listening on port #{server_port}..."
# 接受客戶端連接
client_socket, client_address = server_socket.accept
# 接收客戶端發送的數據
message = client_socket.read(1024)
puts "Received message: #{message}"
# 向客戶端發送響應
response = "Hello, Client!"
client_socket.write(response)
# 關閉套接字
client_socket.close
server_socket.close
首先運行服務器代碼,然后運行客戶端代碼。客戶端將向服務器發送一條消息,服務器將響應一條消息。這個簡單的示例展示了如何使用Ruby的socket
庫進行TCP/IP通信。實際應用中,你可能需要處理錯誤、超時等情況。