Over break, I’ve been experimenting with Ruby a little bit. It’s rather different from the C#/Java syntaxes I’ve leared through schooling. However, I’ve enjoyed using it. And for the reference of myself and others, I’m slapping up a how-to for creating a simple socket server and client.
The Server
require "socket"
serv = TCPServer.new('localhost',7885)
count = 0
loop do
Thread.start(serv.accept) do |s|
count += 1
s.write "You are visitor #{count} to my TCP Ruby Server"
s.close
puts "New visitor: #{count}"
end
end
The server begins by getting the socket library that already comes with Ruby. It then creates an instance of TCPServer, binding it to localhost on port 7885. Count is used to keep track of the number of incoming connections the server receives.
Enter the loop, a new thread will be started upon the blocking method serv.accept and during the life of the thread, it will increment the count, send a message to the visitor, close the connection, and finally write the user count to the console.
The Client
require "socket"
client = TCPSocket.new("localhost",7885)
str = ""
while (add = client.recv(100)) != ""
str += add
end
puts str
client.close
The client simply receives all output sent to it. It opens a connection with localhost on port 7885. After connecting, it recieves a buffer of 100 bytes until no more are read. The buffer is appended to the final output string, and the connection is closed.
And there you have it, a simple Ruby socket connection. From here you can create such things as a web server, or writing your own protocol. Enjoy!