iT邦幫忙

1

创建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 _thread
import socket
import 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 & Port
host="127.0.0.1"
port=5000
s.bind((host,port))
s.listen(5)
clients=[]
#code to allow users to send messages
def 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


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言