在Ruby中进行网络编程,你可以使用一些内置的库,如Socket,或者使用第三方库,如EventMachine或Celluloid。以下是一些基本的网络编程示例:
Ruby的Socket库提供了对BSD套接字接口的访问,可以用来创建TCP或UDP连接。
require 'socket'
server = TCPServer.new('localhost', 2345)
loop do
client = server.accept
puts "客户端已连接:#{client.peeraddr}"
client.puts "Hello from the server!"
client.gets # 等待客户端响应
client.close
end
require 'socket'
client = TCPClient.new('localhost', 2345)
puts client.gets # 读取服务器消息
client.puts "Hello from the client!"
client.close
EventMachine是一个事件驱动的网络库,它可以用来创建高性能的异步TCP/UDP服务器和客户端。
首先,你需要安装eventmachine gem:
gem install eventmachine
然后,你可以创建一个简单的TCP服务器:
require 'eventmachine'
module MyServer
def post_init(socket)
puts "客户端已连接:#{socket.peeraddr}"
socket.write("Hello from the server!\n")
end
def receive_data(socket)
puts "收到来自客户端的数据:#{socket.read}"
socket.write("Server received your message.\n")
end
end
EventMachine.run do
EM.start_server('localhost', 2345, MyServer)
end
require 'eventmachine'
module MyClient
def post_init
puts "已连接到服务器"
send_data("Hello from the client!\n")
end
def receive_data(socket)
puts "收到来自服务器的数据:#{socket.read}"
close if socket.gets.chomp == "Server received your message."
end
end
EM.run do
EM.connect('localhost', 2345, MyClient)
end
Celluloid是一个用于构建并发应用程序的actor模型库。
首先,你需要安装celluloid gem:
gem install celluloid
然后,你可以创建一个简单的TCP服务器:
require 'celluloid'
require 'socket'
class MyServer
include Celluloid
def initialize(host, port)
@host = host
@port = port
start_server
end
def start_server
server = TCPServer.new(@host, @port)
loop do
client = server.accept
spawn do
handle_client(client)
end
end
end
def handle_client(client)
puts "客户端已连接:#{client.peeraddr}"
client.puts "Hello from the server!"
client.gets # 等待客户端响应
client.close
end
end
MyServer.new('localhost', 2345).join
require 'celluloid'
require 'socket'
class MyClient
include Celluloid
def initialize(host, port)
@host = host
@port = port
start_client
end
def start_client
client = TCPSocket.new(@host, @port)
puts client.gets # 读取服务器消息
client.puts "Hello from the client!"
client.close
end
end
MyClient.new('localhost', 2345).join
这些示例展示了如何在Ruby中使用不同的库进行基本的网络编程。你可以根据自己的需求选择合适的库和方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。