Skip to content

Instantly share code, notes, and snippets.

@prem
Forked from dyoder/sockets.rb
Created August 28, 2008 00:52
Show Gist options
  • Save prem/7623 to your computer and use it in GitHub Desktop.
Save prem/7623 to your computer and use it in GitHub Desktop.
require 'socket'
require 'rubygems'
require 'monitor'
include Socket::Constants
class YPCSocket
def initialize( port, ip )
@socket = Socket.new( AF_INET, SOCK_STREAM, 0 )
@address = Socket.pack_sockaddr_in( port, ip )
end
def close ; @socket.close ; end
def listen
@socket.bind( @address )
@socket.listen( 1 )
end
def connect
@socket.connect( @address )
end
def accept
Connection.new( @socket.accept.first )
end
class Connection
def initialize( socket )
@socket = socket
end
def read ; @socket.gets.chomp ; end
end
end
def read(connection)
#connection = client.accept
while ( data = connection.read && data != 'END' )
lock.synchronize { buf << data }
end
stop = true
end
def write
until( stop ) do
lock.synchronize { data = buf.pop unless buf.empty? }
server.puts( data ) if data
end
end
lock = Mutex.new ; buf = []
client = YPCSocket.new( 2201, '10.45.10.219' )
client.listen
server = YPCSocket.new( 2202, '10.45.10.219' ).connect
stop = false
while true
c = client.accept
Thread.start { read(c) }
Thread.start { write }
end
client.close
server.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment