04-06-2010, 06:43 PM
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.
Client code:
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.
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.