这篇文章是copy的,我自己写的不能把每个人发送的数据在别人的屏幕上显示!先把他的保存在我这里看下!
1 #!/usr/bin/env python 2 #coding:utf-8 3 4 import socket 5 import sys 6 import threading 7 8 con = threading.Condition() 9 HOST = raw_input("input the server's ip adrress: ") # Symbolic name meaning all available interfaces10 PORT = 8888 # Arbitrary non-privileged port11 data = ''12 13 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)14 print 'Socket created'15 s.bind((HOST, PORT))16 s.listen(10)17 print 'Socket now listening'18 19 #Function for handling connections. This will be used to create threads20 def clientThreadIn(conn, nick):21 global data22 #infinite loop so that function do not terminate and thread do not end.23 while True:24 #Receiving from client25 try:26 temp = conn.recv(1024)27 if not temp:28 conn.close()29 return30 NotifyAll(temp)31 print data32 except:33 NotifyAll(nick + " leaves the room!")34 print data35 return36 37 #came out of loop38 39 def NotifyAll(sss):40 global data41 if con.acquire():42 data = sss43 con.notifyAll()44 con.release()45 46 def ClientThreadOut(conn, nick):47 global data48 while True:49 if con.acquire():50 con.wait()51 if data:52 try:53 conn.send(data)54 con.release()55 except:56 con.release()57 return58 59 60 while 1:61 #wait to accept a connection - blocking call62 conn, addr = s.accept()63 print 'Connected with ' + addr[0] + ':' + str(addr[1])64 nick = conn.recv(1024)65 #send only takes string66 #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.67 NotifyAll('Welcome ' + nick + ' to the room!')68 print data69 print str((threading.activeCount() + 1) / 2) + ' person(s)!'70 conn.send(data)71 threading.Thread(target = clientThreadIn , args = (conn, nick)).start()72 threading.Thread(target = ClientThreadOut , args = (conn, nick)).start()73 74 s.close()
下面的是客户端代码:
1 #!/usr/bin/env python 2 #coding:utf-8 3 4 import socket 5 import threading 6 7 8 inString = '' 9 outString = ''10 nick = ''11 12 def DealOut(s):13 global nick, outString14 while True:15 outString = raw_input()16 outString = nick + ': ' + outString17 s.send(outString)18 19 def DealIn(s):20 global inString21 while True:22 try:23 inString = s.recv(1024)24 if not inString:25 break26 if outString != inString:27 print inString28 except:29 break30 31 32 nick = raw_input("input your nickname: ")33 ip = raw_input("input the server's ip adrress: ")34 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)35 sock.connect((ip, 8888))36 sock.send(nick)37 38 thin = threading.Thread(target = DealIn, args = (sock,))39 thin.start()40 thout = threading.Thread(target = DealOut, args = (sock,))41 thout.start()42 43 #sock.close()