Created
March 31, 2011 09:35
-
-
Save TvL2386/896112 to your computer and use it in GitHub Desktop.
Workshop ruby 1: client.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
require 'thread' | |
class Client | |
def initialize server_name, server_port | |
@server_name, @server_port = server_name, server_port | |
end | |
def connect | |
@socket = TCPSocket.new(@server_name, @server_port) | |
puts "Connected to server" | |
end | |
def send_message message | |
@socket.write message | |
end | |
def print_message | |
Thread.new do | |
loop do | |
# monitor socket and print data if there is any | |
result = IO.select([@socket], nil, nil, nil) | |
if not result.nil? | |
socket = result[0].first # result[0] is the socket array. In this example there can only be one | |
data = socket.readpartial 4096 | |
# use print here, because puts automatically appends a newline | |
print data | |
end | |
end | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment