溫馨提示×

Ruby TCP/IP通信如何傳輸數(shù)據(jù)

小樊
82
2024-11-03 03:38:42
欄目: 編程語言

在Ruby中,可以使用socket庫進(jìn)行TCP/IP通信

  1. 創(chuàng)建一個TCP客戶端:
require 'socket'

# 創(chuàng)建一個TCP套接字
client_socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM)

# 連接到服務(wù)器
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)

# 向服務(wù)器發(fā)送數(shù)據(jù)
message = "Hello, Server!"
client_socket.write(message)

# 接收服務(wù)器的響應(yīng)
response = client_socket.read(1024)
puts "Server response: #{response}"

# 關(guān)閉套接字
client_socket.close
  1. 創(chuàng)建一個TCP服務(wù)器:
require 'socket'

# 創(chuàng)建一個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)

# 開始監(jiān)聽連接
server_socket.listen(1)

puts "Server is listening on port #{server_port}..."

# 接受客戶端連接
client_socket, client_address = server_socket.accept

# 接收客戶端發(fā)送的數(shù)據(jù)
message = client_socket.read(1024)
puts "Received message: #{message}"

# 向客戶端發(fā)送響應(yīng)
response = "Hello, Client!"
client_socket.write(response)

# 關(guān)閉套接字
client_socket.close
server_socket.close

首先運(yùn)行服務(wù)器代碼,然后運(yùn)行客戶端代碼。客戶端將向服務(wù)器發(fā)送一條消息,服務(wù)器將響應(yīng)一條消息。這個簡單的示例展示了如何使用Ruby的socket庫進(jìn)行TCP/IP通信。實(shí)際應(yīng)用中,你可能需要處理錯誤、超時等情況。

0