Python教程

python网络编程之TCP

本文主要是介绍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]

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


这篇关于python网络编程之TCP的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!