Do I get points for being the first answer?
The Server:
PHP Code:
#!/usr/bin/env python
import socket, select
HOST = 'localhost'
PORT = 9001
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(3)
connections = [server]
def send(connection, message):
connection.send(message + '\r\n')
while True:
ready_connections = select.select(connections, [], [])[0]
for connection in ready_connections:
if connection is server:
connect, address = server.accept()
connections.append(connect)
print 'Connected: ' + address[0]
for con in connections:
if con is not server and con is not connect:
send(con, address[0] + ' JOIN')
else:
message = connection.recv(512)
if message:
address = connection.getsockname()[0]
print 'Recieved From ' + connection.getsockname()[0] + ' :' + message
for con in connections:
if con is not server and con is not connection:
send(con, address + ' MSG :' + message)
else:
address = connection.getsockname()[0]
print 'Disconnected: ' + address
connection.close()
connections.remove(connection)
for con in connections:
if con is not server and con is not connection:
send(con, address + ' QUIT')
And The Client:
PHP Code:
#!/usr/bin/env python
import socket, threading
HOST = 'localhost'
PORT = 9001
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
def listen():
while True:
data = client.recv(512)[:-2].split()
who = data[0]
command = data[1]
args = data[2:]
if command == 'MSG':
print who + ': ' + ' '.join(args)[1:]
if command == 'JOIN':
print '--> ' + who + ' has joined'
if command == 'QUIT':
print '<-- ' + who + ' has quit'
def send():
while True:
try:
message = raw_input('')
except KeyboardInterrupt:
message = 'quit'
print
if message.lower() == 'quit':
client.close()
exit()
client.send(message + '\r\n')
thread1 = threading.Thread(target = listen)
thread2 = threading.Thread(target = send)
thread1.start()
thread2.run()
EDIT: Ooops, forgot something. It'll work, but...
Bookmarks