创建Python聊天室的最佳方法

您好,我们又回来了另一个Python #DIY教程。 今天,我们要去一个Python聊天室,或者您可以说易于理解和运行的Python Chatbox。
Img

它是如何工作的?

Python Chatbox简要地使用了套接字编程和多线程的概念。 聊天机器人的脚本中有两个部分,即称为socketserver.py的服务器端程序和称为chat.py的客户端程序。 它可以帮助聊天室或聊天框同时与多个用户连接。

如何建立?

在桌面上创建一个名为python chatbox的文件夹,您可以在其中放置所有文件。将文件拖到您的代码中,并创建两个文件,即chat.py [客户端脚本] / [GUI部件]和socketserver.py [服务器端脚本]。请遵循以下代码,并按照标记将其放在相应的文件中。首先执行python socketserver.py,然后执行python chat.py来运行程序。

socketserver.py

## Python代码可做聊天室的服务器端部分。import _threadimport socketimport threading"""AF_INET is the address domain of the socket. This is used when we have an Internet Domain with any two hosts The 2nd context of the code is the type of socket. """s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)  s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)# piece of code to allow IP address & Porthost="127.0.0.1"port=5000s.bind((host,port))s.listen(5)clients=[]#code to allow users to send messagesdef connectNewClient(c):     while True:        global clients        msg = c.recv(2048)        msg ='Online ('+str(clients.index(c)+1)+'):  '+msg.decode('ascii')        sendToAll(msg,c)def sendToAll(msg,con):    for client in clients:        client.send(msg.encode('ascii'))         while True:    c,ad=s.accept()    # Display message when user connects    print('*服务器已连接 ')    clients.append(c)    c.send(('Online ('+str(clients.index(c)+1)+')').encode('ascii'))    _thread.start_new_thread(connectNewClient,(c,))

由于gui代码很长,所以我单独给出了 Python Chat box


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章