Support Forums
[Tutorial] Simple Multi-Client TCP Server - Printable Version

+- Support Forums (https://www.supportforums.net)
+-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87)
+--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18)
+---- Forum: Ruby and Ruby on Rails (https://www.supportforums.net/forumdisplay.php?fid=55)
+---- Thread: [Tutorial] Simple Multi-Client TCP Server (/showthread.php?tid=5724)



[Tutorial] Simple Multi-Client TCP Server - Wolskie - 04-06-2010

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.


RE: [Tutorial] Simple Multi-Client TCP Server - Bursihido - 12-13-2010

Awesome share mate Thanks


RE: [Tutorial] Simple Multi-Client TCP Server - Crystal - 05-22-2011

Nice tut Smile
Thanks helped mee out Big Grin


RE: [Tutorial] Simple Multi-Client TCP Server - +Moon - 06-18-2011

Ah, very elegant. I don't have any programming experience in networking/sockets, but it's nice to know that it's that simple.