Created
April 27, 2014 20:56
-
-
Save olimagsax/11355501 to your computer and use it in GitHub Desktop.
Simple Client/Server connection !
This file contains hidden or 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
#!/usr/bin/env ruby -w | |
require "socket" | |
class Client | |
def initialize( server ) | |
@server = server | |
@request = nil | |
@response = nil | |
listen | |
send | |
@request.join | |
@response.join | |
end | |
def listen | |
@response = Thread.new do | |
loop { | |
msg = @server.gets.chomp | |
puts "#{msg}" | |
} | |
end | |
end | |
def send | |
puts "Enter the username:" | |
@request = Thread.new do | |
loop { | |
msg = $stdin.gets.chomp | |
@server.puts( msg ) | |
} | |
end | |
end | |
end | |
server = TCPSocket.open( "localhost", 3000 ) | |
Client.new( server ) |
This file contains hidden or 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
#!/usr/bin/env ruby -w | |
require "socket" | |
class Server | |
def initialize( port, ip ) | |
@server = TCPServer.open( ip, port ) | |
@connections = Hash.new | |
@rooms = Hash.new | |
@clients = Hash.new | |
@connections[:server] = @server | |
@connections[:rooms] = @rooms | |
@connections[:clients] = @clients | |
puts "Le serveur est allumé, et en attente :" | |
run | |
end | |
def run | |
loop { | |
Thread.start(@server.accept) do | client | | |
nick_name = client.gets.chomp.to_sym | |
@connections[:clients].each do |other_name, other_client| | |
if nick_name == other_name || client == other_client | |
client.puts "Ce nom d'utilisateur est déjà employé !" | |
Thread.kill self | |
end | |
end | |
puts "#{nick_name} #{client}" | |
@connections[:clients][nick_name] = client | |
client.puts "Connection établie ! Les autres peuvent desormais t'entendre !" | |
listen_user_messages( nick_name, client ) | |
end | |
}.join | |
end | |
def listen_user_messages( username, client ) | |
loop { | |
msg = client.gets.chomp | |
@connections[:clients].each do |other_name, other_client| | |
unless other_name == username | |
other_client.puts "#{username.to_s}: #{msg}" | |
end | |
end | |
} | |
end | |
end | |
puts "Entrez l'ip du serveur :" | |
ip = $stdin.gets.chomp | |
puts "Entrez le port à ouvrir :" | |
port = $stdin.gets.chomp | |
Server.new( port, ip ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment