欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python socket通信

程序员文章站 2022-03-24 11:38:24
...
#client.py
from socketserver import BaseRequestHandler, TCPServer
# from collect_data import HouseStark
#指定接收消息的客户端ip列表
import os

target_clients = ["xxxxxxx",'xxxxxxx','xxxxxxx','xxxxxxxx']

class EchoHandler(BaseRequestHandler):
    def handle(self):
        for target_client in target_clients:
            if target_client in self.client_address:
                print('Got connection from', self.client_address)
                msg = self.request.recv(8192)
                if not msg:
                    break

                cmd = str(msg, encoding = "gbk")


                # aa = HouseStark.ArgvHandler(cmd)
                # bb = aa.parse_argv()

                # print(b.read(),'xxxxxxxxxxxxxxxx')
                ret_msg = bytes(str(bb), encoding="utf-8")
                print(ret_msg)
                self.request.send(ret_msg)
                break

if __name__ == '__main__':
    from threading import Thread
    NWORKERS = 16
    #绑定socket服务端所在ip和端口号
    serv = TCPServer(('', 9999), EchoHandler)
    for n in range(NWORKERS):
        t = Thread(target=serv.serve_forever)
        t.daemon = True
        t.start()
    serv.serve_forever()
#server.py
from socket import socket,AF_INET,SOCK_STREAM
import os
#服务端的ip地址
server_ip = 'xxxxxxxx'
#服务端socket绑定的端口号
server_port = 9999

if __name__ == '__main__':
    while True:
        str_msg = input("请输入要发送信息:")
        if str_msg != "":
            bytes_msg = bytes(str_msg, encoding = "utf-8")
            client = socket(AF_INET,SOCK_STREAM)
            client.connect((server_ip,server_port))
            client.send(bytes_msg)
            print(str(client.recv(8192),encoding="utf-8"))
            client.close()