Python制作一个简单聊天室 -《狗嗨默示录》-
client.py
# !/usr/bin/env python # -*- coding: utf-8 -*- import socket import threading outString = '' inString = '' def client_send(sock): global outString while True: #监听输入 outString = input() #接收输入 outString = nick + ' : ' + outString sock.send(outString.encode('utf-8')) def client_accept(sock): global inString while True: try: inString = sock.recv(1024).decode('utf-8') #接收数据 if not inString: break if outString != inString: print(inString) except: break nick = input('input your nickname:') ip = input('input the server ip address:') port = 8888 sock = socket.socket()#建立套接字 sock.connect((ip,port)) #连接 sock.send(nick.encode('utf-8')) th_send = threading.Thread(target=client_send,args=(sock,)) th_send.start() th_accept = threading.Thread(target=client_accept,args=(sock,)) th_accept.start()
server.py
# !/usr/bin/env python # -*- coding:utf-8 -*- import socket import threading host = input('input the server ip address:') port = 8888 data = '' #文本数据 s = socket.socket() #创建套接字 print('Socket created') s.bind((host,port)) #绑定 s.listen(10) #监听连接 print('Socket new listening') cond = threading.Condition() #条件 def Notify_All(info): global data if cond.acquire(): #获取 data = info cond.notifyAll() #通知 cond.release() #释放 def ThreadOut(conn,nick): #发送消息 global data while True: if cond.acquire(): cond.wait() #等待 if data: try: conn.send(data.encode('utf-8')) cond.release() except: cond.release() return def ThreadIn(conn,nick): #接收消息 global data while True: try: info = conn.recv(1024).decode('utf-8') if not info: conn.close() return Notify_All(info) print(data) except: Notify_All(nick + ' 掉线') print(data) return while True: conn,addr = s.accept() #接受连接,addr包含ip,port print('Connected with '+addr[0]+' : '+str(addr[1])) nick = conn.recv(1024).decode('utf-8') welcome = 'Welcome '+ nick +' to the room(〃`▽`〃)' Notify_All(welcome) print(data) conn.send(data.encode('utf-8')) threading.Thread(target=ThreadOut,args=(conn,nick)).start() threading.Thread(target=ThreadIn,args=(conn,nick)).start()