使用socket实现简单聊天室
Posted zhan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用socket实现简单聊天室相关的知识,希望对你有一定的参考价值。
通过socket实现简单的聊天室
1、服务端代码:serverselect.py
#!/usr/bin/env python #coding:utf8 import socket import select class SelectServer(object): def __init__(self,host,port,backlog): self.host = host self.prot = port self.address = (host,port) self.backlog = backlog socket.server = None self.socketList = list() def _initSocket(self): self.server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.server.bind(self.address) self.server.listen(self.backlog) self.socketList.append(self.server) print("chat room has start") while 1 : rlist,wlist ,elist = select.select(self.socketList,[],[]) for r in rlist: if r == self.server: ServrtConn,clientAddr = self.server.accept() self.socketList.append(ServrtConn) print("{0}进入房间".format(clientAddr)) self.broadcast(r,"{0}进入房间".format(clientAddr)) else: try: data = r.recv(2048) if data: self.broadcast(r, "{0}:{1}".format(clientAddr, ServrtConn)) print("{0} say:{1}".format(clientAddr,data)) except Exception as e: self.broadcast(r, "{0} 下线".format(clientAddr)) print("{0}下线".format(clientAddr)) r.close() self.socketList.remove(r) def broadcast(self,r,data): for i in self.socketList: if i != r and i != self.server: try: i.sendall(data) except Exception as e : i.close() self.socketList.remove(i) def main(): selectServer = SelectServer(host="192.168.88.100",port=4321,backlog=5) selectServer._initSocket() if __name__ == "__main__": main()
2、客户端代码:clientselect.py
#!/usr/bin/env python #coding:utf8 import socket,select,string,sys import time if __name__ == "__main__": host = "192.168.88.100" port = 4321 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.settimeout(2) try: s.connect((host,port)) except : print("Unable to connect") sys.exit() print(\'Connected to remote host. Start sending messages\') while 1 : rlist = [sys.stdin,s] read_list, write_list, error_list = select.select(rlist, [], []) for sock in read_list: if sock == s : data = sock.recv(2048) if not data : continue else: sys.stdout.write(data) else: msg = raw_input("i say:") # print(msg) s.sendall(msg)
运行结果:
服务端:
客户端:
服务端收到客户端的请求:
以上是关于使用socket实现简单聊天室的主要内容,如果未能解决你的问题,请参考以下文章
游戏开发实战Unity使用Socket通信实现简单的多人聊天室(万字详解 | 网络 | TCP | 通信 | Mirror | Networking)
游戏开发实战Unity使用Socket通信实现简单的多人聊天室(万字详解 | 网络 | TCP | 通信 | Mirror | Networking)