Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tutorial] Simple Multi-Client TCP Server
#1
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.
Reply
#2
Awesome share mate Thanks
Reply
#3
Nice tut Smile
Thanks helped mee out Big Grin
[Image: IYOy9.png]
Reply
#4
Ah, very elegant. I don't have any programming experience in networking/sockets, but it's nice to know that it's that simple.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)