Support Forums

Full Version: [Tutorial] Simple Multi-Client TCP Server
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In Ruby like many other languages we can use sockets to transfer information to different computers throughout the network and internet. Sockets are a very useful component.

Here is an example server that takes receives input from a client and prints it on the screen.


Code:
#!/usr/bin/env ruby
require('socket')
server = TCPServer.new(14776) # Listen on port 14776

loop do
  Thread.start(server.accept) do |client|
    received = client.gets
    $stdout.puts received
  end
end

Client code:
Code:
#!/usr/bin/env ruby
require('socket')
s = TCPSocket.new("localhost", 14776)
s.puts("Hello Server")


When the server is run then the client is run, the server will print out "Hello Server".
This message was sent from the client. The server received the information from the client and printed it on the screen.

We create a thread for each client that connects so we can handle many at once.
Awesome share mate Thanks
Nice tut Smile
Thanks helped mee out Big Grin
Ah, very elegant. I don't have any programming experience in networking/sockets, but it's nice to know that it's that simple.