Skip to content

Instantly share code, notes, and snippets.

@jxcl
Created June 15, 2010 18:34
Show Gist options
  • Save jxcl/439485 to your computer and use it in GitHub Desktop.
Save jxcl/439485 to your computer and use it in GitHub Desktop.
import socket
import threading
import Queue
import time
def wait_for_connection():
HOST = 'localhost'
PORT = 49999
new_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new_connection.bind((HOST, PORT))
new_connection.listen(1)
conn, addr = new_connection.accept()
return conn
def connect_to_server(ip):
HOST = ip
PORT = 49999
new_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
new_connection.connect((HOST, PORT))
return new_connection
def send_to_all(word, player, conn_list):
for connection in conn_list:
pass
class connected_client(threading.Thread):
def __init__ (self, connection, queue):
threading.Thread.__init__(self)
self.connection = connection
self.queue = queue
def run(self):
print '"connected_client" running'
self.connection.send('[Dummy data][more dummy data]')
self.connection.send(self.queue.get())
class await_connections(threading.Thread):
def __init__(self, connection_queue, event_queue):
threading.Thread.__init__(self)
self.connection_queue = connection_queue
def run(self):
while (1):
print 'Waiting for connection...'
new_connection = wait_for_connection()
print 'Detected connection.'
client = connected_client(new_connection, event_queue)
print 'Thread created.'
client.start()
print 'Accepted a connection.'
if __name__ == '__main__':
is_server = int(raw_input("Is this the server? "))
if is_server:
event_q = Queue.Queue(0)
conn_q = Queue.Queue(0)
wait = await_connections(conn_q, event_q)
wait.start()
while(1):
'''connection = conn_q.get()
client = connected_client(connection, event_q)
client.start()'''
command = raw_input('Send to clients:')
event_q.put('[' + command + ']')
else:
connection = connect_to_server('127.0.0.1')
while(1):
recvd = ''
while(1):
data = connection.recv(1024)
if not data:
break
recvd += data
command = ''
for x in range(len(recvd)):
if recvd[x] == '[':
command = ''
elif recvd[x] == ']':
recvd = recvd[x+1:]
print command
x = 0
else:
command += recvd[x]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment