服务器端:
1 # -*- coding: utf-8 -*- 2 import socket, threading 3 4 con = threading.Condition() 5 HOST = raw_input("input the server's ip adrress: ") # Symbolic name meaning all available interfaces 6 PORT = 8888 # Arbitrary non-privileged port 7 data = '' 8 9 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 10 print 'Socket created' 11 s.bind((HOST, PORT)) 12 s.listen(10) 13 print 'Socket now listening' 14 15 #Function for handling connections. This will be used to create threads 16 def clientThreadIn(conn, nick): 17 global data 18 #infinite loop so that function do not terminate and thread do not end. 19 while True: 20 #Receiving from client 21 try: 22 temp = conn.recv(1024) 23 if not temp: 24 conn.close() 25 return 26 NotifyAll(temp) 27 print data 28 except: 29 NotifyAll(nick + " leaves the room!") 30 print data 31 return 32 33 #came out of loop 34 35 def NotifyAll(sss): 36 global data 37 if con.acquire(): 38 data = sss 39 con.notifyAll() 40 con.release() 41 42 def ClientThreadOut(conn, nick): 43 global data 44 while True: 45 if con.acquire(): 46 con.wait() #notifyAll effect there 47 if data: 48 try: 49 conn.send(data) 50 con.release() 51 except: 52 con.release() 53 return 54 55 56 while 1: 57 #wait to accept a connection - blocking call 58 conn, addr = s.accept() 59 print 'Connected with ' + addr[0] + ':' + str(addr[1]) 60 nick = conn.recv(1024) 61 #send only takes string 62 #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function. 63 NotifyAll('Welcome ' + nick + ' to the room!') 64 print data 65 print str((threading.activeCount() + 1) / 2) + ' person(s)!' 66 conn.send(data) 67 threading.Thread(target = clientThreadIn , args = (conn, nick)).start() 68 threading.Thread(target = ClientThreadOut , args = (conn, nick)).start() 69 70 s.close()
客户端:
1 # -*- coding: utf-8 -*- 2 import socket, threading 3 4 inString = '' 5 outString = '' 6 nick = '' 7 8 def DealOut(s): 9 global nick, outString 10 while True: 11 outString = raw_input() 12 outString = nick + ': ' + outString 13 s.send(outString) 14 15 def DealIn(s): 16 global inString 17 while True: 18 try: 19 inString = s.recv(1024) 20 if not inString: 21 break 22 if outString != inString: 23 print inString 24 except: 25 break 26 27 nick = raw_input("input your nickname: ") 28 ip = raw_input("input the server's ip adrress: ") 29 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 30 sock.connect((ip, 8888)) 31 sock.send(nick) 32 33 thin = threading.Thread(target = DealIn, args = (sock,)) 34 thin.start() 35 thout = threading.Thread(target = DealOut, args = (sock,)) 36 thout.start()
我把服务器端代码放到我在阿里云买的服务器上运行后在本地运行客户端程序(ip输入服务器ip)即可进行聊天室程序:
服务器端:
两个客户端: