python编程基础训练之网络编程简单多人在线聊天

回顾

python编程基础训练之网络编程简单多人在线聊天_第1张图片

python编程基础训练之网络编程简单多人在线聊天_第2张图片

python编程基础训练之网络编程简单多人在线聊天_第3张图片

 也可以看看这个网址的基础内容:https://www.runoob.com/python3/python3-socket.html

1、服务器端代码:

import socket
from threading import Thread
import threading
import datetime

clientSocket=[]#一个列表,内部存储元组元素(所有参与链接的客户端),(conn,字符串(address),例如(127.0.0.1,"127.0.0.1",9000)

class Server(Thread):#继承多线程
    def __init__(self,name):
        super().__init__()
        self.name = name
        self.ip_port = ('127.0.0.1', 9000)#127.0.0.1就是本机IP,9000为端口号
        self.init()
        print("服务端开启...")

    def init(self):
        self.sk = socket.socket()
        self.sk.bind(self.ip_port)
        self.sk.listen(10)

    def run(self):
        while True:
            try:
                conn, address = self.sk.accept()
                clientSocket.append((conn, str(address)))
                nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 当前时间
                str1 = "[" + str(nowTime) + "]>>" + str(address) + ":加入群聊"  # 某IP,port的某用户x加入群聊
                print(str1)
                for con in clientSocket:
                    con[0].sendall(bytes(str1, encoding='utf-8'))  # 向每个客户端发送某人加入群聊的通知信息
                client_thread = threading.Thread(target=self.handle_ac,args=(conn, str(address)))  # 把sock加入线程内
                client_thread.start()  # 启动线程
            except Exception as e:
                print("[" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "]>>run死循环:",e.args)

    def handle_ac(self,conn,address):
        while True:
            connection=()
            try:
                data = str(conn.recv(1024), encoding='utf -8')
                nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 当前时间
                str1 = "[" + str(nowTime) + "]>>" + str(address) + ":" + data  # 某IP,port的某用户x当前时间发送的消息data
                print(str1)  # 服务器端也打印群聊信息消息记录  log
                for con in clientSocket:
                    try:
                        con[0].sendall(bytes(str1, encoding='utf-8'))  # 服务器将用户x(address:(IP,port))发送出来的群聊数据发送给每个客户端用户
                    except Exception as e:
                        clientSocket.remove(con)#若该客户端连接不通,说明客户端存在问题或者关闭,直接从客户端存储列表里剔除该客户端
            except Exception as e:
                print("[" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "]>>handle_ac死循环:",e.args)
                self.join()

    def close(self):
        for con in clientSocket:
            con[0].close()#将列表里每个元组第一个conn链接全部关闭
        self.sk.close()

if __name__=="__main__":
    server = Server("server1")
    server.start()

2、客户端代码:

import socket
from threading import Thread
class Client(Thread):
    def __init__(self,name):
        super(Client, self).__init__()
        self.name = name
        self.ip_port = ('127.0.0.1', 9000)
        self.sk = socket.socket()
        self.sk.connect(self.ip_port)
        print("连接成功!!!")

    def run(self):#负责接收服务器端发来的消息打印处理
        try:
            while True:
                data = str(self.sk.recv(1024), encoding='utf-8')
                print(data)
        except Exception as e:
            print("服务端已关闭..")
            return

    def send(self):#负责本客户端输入信息发送到服务器端
        try:
            while True:
                inp = input()
                self.sk.sendall(bytes(inp, encoding='utf-8'))
        except Exception as e:
            print("服务端已关闭..")
            return

    def close(self):
        self.sk.close()

if __name__=="__main__":
    client1 = Client("client1")
    client1.start()#数据接收与数据发送并行执行
    client1.send()#数据接收与数据发送并行执行

 3、运行结果:

python编程基础训练之网络编程简单多人在线聊天_第4张图片

python编程基础训练之网络编程简单多人在线聊天_第5张图片

python编程基础训练之网络编程简单多人在线聊天_第6张图片

python编程基础训练之网络编程简单多人在线聊天_第7张图片

 

你可能感兴趣的:(python)