运行情况

服务端

python 智能聊天 python 在线聊天_websocket

客户端

python 智能聊天 python 在线聊天_python_02

服务端代码

import socket
import threading

# 创建TCP Socket, 类型为服务器之间网络通信,流式Socket
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定服务器端的IP和端口
mySocket.bind(('127.0.0.1', 5000))
# 开始监听TCP传入连接,并设置操作系统可以挂起的最大连接数量
mySocket.listen(5)

print('Server was started by ', socket.gethostbyname('localhost'), 'now is listening ...')
# 创建字典,用于存储客户端的用户
mydict = dict()
# 创建列表,用于存储客户端的连接
mylist = list()

# 把聊天信息发送给除自己以外的所有人
def chatMsgToOthers(exceptMe, chatMsg):
    for c in mylist:
        if c.fileno() != exceptMe:
            try:
                # 向客户端发送消息
                c.send(chatMsg.encode())
            except:
                pass

# 保持与客户端连接的子线程的处理逻辑
def subThreadProcess(myconnection, connNum):
    # 接收客户端消息
    username = myconnection.recv(1024).decode()
    mydict[myconnection.fileno()] = username
    mylist.append(myconnection)
    print('client connection number:', connNum, ' has nickname:', username)
    chatMsgToOthers(connNum, '【系统提示】:' + username + '已经进入聊天室,请文明聊天')
    while True:
        try:
            # 接收客户端消息
            recvedMsg = myconnection.recv(1024).decode()
            if recvedMsg:
                print(mydict[connNum], ': ', recvedMsg)
                chatMsgToOthers(connNum, mydict[connNum] + ': ' + recvedMsg)
        except (OSError, ConnectionResetError):
            try:
                mylist.remove(myconnection)
            except:
                pass
            print(mydict[connNum], 'was exit, ', len(mylist), ' person left!')
            chatMsgToOthers(connNum, '【系统提示】:' + mydict[connNum] + ' 已经离开')
            myconnection.close()
            return

while True:
    # 接受TCP连接并返回(connection,address),其中connection是新的Socket对象,可以用来接收和发送数据,address是连接客户端的地址。
    connection, address = mySocket.accept()
    print('Accept a new connection', connection.getsockname(), connection.fileno())
    try:
        # 接收客户端消息
        buf = connection.recv(1024).decode()
        if buf == '1':
            # 向客户端发送消息
            connection.send(b'connection success, welcome to chat room!')
            # 为当前连接创建一个新的子线程来保持通信
            myThread = threading.Thread(target=subThreadProcess, args=(connection, connection.fileno()))
            myThread.setDaemon(True)
            myThread.start()
        else:
            # 向客户端发送消息
            connection.send(b'connection fail, please go out!')
            connection.close()
    except:
        pass

客户端代码

import socket
import threading

# 创建TCP Socket, 类型为服务器之间网络通信,流式Socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 通过IP和端口号连接服务器端Socket, 类型为服务器之间网络通信,流式Socket
sock.connect(('127.0.0.1', 5000))
# 向服务器发送连接请求
sock.send(b'1')
# 从服务器接收到的消息
print(sock.recv(1024).decode())
username = input('请输入你的昵称: ')
# 向服务器发送聊天用户名
sock.send(username.encode())

# 向服务器端发送消息的处理逻辑
def sendThreadProcess():
    while True:
        try:
            myMsg = input('me: ')
            sock.send(myMsg.encode())
        except ConnectionAbortedError:
            print('Server closed this connection!')
        except ConnectionResetError:
            print('Server is closed!')

# 向服务器端接收消息的处理逻辑
def recvThreadProcess():
    while True:
        try:
            otherMsg = sock.recv(1024)
            if otherMsg:
                print(otherMsg.decode())
            else:
                pass
        except ConnectionAbortedError:
            print('Server closed this connection!')

        except ConnectionResetError:
            print('Server is closed!')

# 创建发送和接收消息的子线程
sendThread = threading.Thread(target=sendThreadProcess)
recvThread = threading.Thread(target=recvThreadProcess)
threads = [sendThread, recvThread]

for t in threads:
    t.setDaemon(True)
    t.start()
t.join()