python网络编程之TCP

python网络编程之TCP

TCP中服务器端server_socket = socket(AF_INET,SOCK_STREAM)
​ 客户端:client.py

    from socket import *
    from threading import Thread
    from tcp.client_handler import *


    def main():
        client_socket = socket(AF_INET, SOCK_STREAM)
        client_socket.connect(('localhost', 8888))
        user_name = input("用户名:")
        client_socket.send(user_name.encode("utf-8"))
        Thread(target=sendMsg, args=(client_socket,)).start()
        Thread(target=receiveMsg, args=(client_socket,)).start()


    if __name__ == '__main__':
        main()

客户端处理:client_handler.py

import json


def sendMsg(client_socket):
    while True:
        input_msg = input().split("@")
        if len(input_msg) == 1:
            msg = input_msg[0]
            toPerson = "all"
        elif len(input_msg) == 2:
            msg = input_msg[0]
            toPerson = input_msg[1]
        else:
            print("注意格式,消息@对方用户名")
        data = {"msg": msg, "toPerson": toPerson}
        data = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=True)
        client_socket.send(data.encode("utf-8"))


def receiveMsg(client_socket):
    while True:
        msg = client_socket.recv(1024)
        print(msg.decode("utf-8"))

​ 服务器端:server.py

from socket import *
from threading import Thread
from tcp.server_handler import *


def main():
 server_socket = socket(AF_INET, SOCK_STREAM)
 server_socket.bind(('localhost', 8888))
 server_socket.listen(5)
 map = {}
 while True:
     try:
         client_socket, client_info = server_socket.accept()
         user_name = client_socket.recv(1024).decode("utf-8")
         print(user_name + "上线了。。。")
         map[user_name] = client_socket
         Thread(target=handler, args=(client_socket, map)).start()
     except Exception as e:
         print(e)


if __name__ == '__main__':
 main()

​ 服务器处理:server_handler.py

import json
def handler(client_socket, map):
    user_name = findKey(client_socket, map)
    while True:
        try:
            data = client_socket.recv(1024)
            data = json.loads(data)
            msg = data["msg"]
            toPerson = data["toPerson"]
            if "all".endswith(toPerson):
                msg = user_name + ":" + msg
                for key in map.keys():
                    if user_name.endswith(key):
                        continue
                    map[key].send(msg.encode("utf-8"))
            else:
                msg = user_name + "对您私聊说:" + msg
                map[toPerson].send(msg.encode("utf-8"))
        except Exception as e:
            print(user_name+"下线了。。。")
            map.pop(user_name)
            client_socket.close()
            break

def findKey(client_socket, map):
    key_list = []
    value_list = []
    for key, value in map.items():
        key_list.append(key)
        value_list.append(value)
    if client_socket in value_list:
        value_index = value_list.index(client_socket)
    return key_list[value_index]

运行结果:(先运行服务器,再运行多个客户端)


posted @ 2021-09-08 20:43  计院阮小杰  阅读(141)  评论(0编辑  收藏  举报