1#
bleem1998 发表于 2007-07-15 23:44
最简单的聊天室,出错鸟,大家帮看看?
和同事楼上楼下经常要交流
所以写了个这个服务器
大家telneet上去之后就可以说话
但是断开的时候有问题
咋回事儿啊?
[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/env python
import socket, sys
import threading
import time
import random
HOST="0.0.0.0" #localhost
PORT=5000
if len(sys.argv) > 1:
PORT = int(sys.argv[1])
conn_list = []
class GetClient(threading.Thread):
def __init__(self, conn, addr):
threading.Thread.__init__(self, name = str(addr[0]))
self.conn = conn
self.addr = addr
print '---> Connection received from:', addr[0], addr[1]
def run(self):
while True:
packet = self.conn.recv(1024)
if not packet:
print '---> %s:%s closed\n' % (addr[0], addr[1])
conn_list.remove(conn)
print 'conn_list length[%d]' % len(conn_list)
break
else:
for c in conn_list:
c.send('[' + addr[0] + ']: ' + packet)
# self.conn.send(packet)
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
mysocket.bind((HOST, PORT))
except socket.error:
sys.exit("bind %d port error" % PORT)
while True:
print 'Waitting for connection...'
mysocket.listen(5)
conn, addr = mysocket.accept()
print 'conn id(%d)' % id(conn)
conn_list.append(conn)
thread = GetClient(conn, addr)
thread.start()
print 'Server shutdown....'
mysocket.close()
sys.exit(0)
|