python socket 通信

import os
import socket
import threading

class SocketServerThread(threading.Thread):
    def __init__(self, addr="127.0.0.1", port=3333, notify=None):
        threading.Thread.__init__(self, name="socketThread", daemon=True)
        self.addr = addr
        self.port = port
        self.notify = notify
        self.client = None

    def run(self):
        with socket.create_server((self.addr, self.port)) as server:
            print("[Socket] listen on {}:{}".format(self.addr, self.port))
            while True:
                conn, addr = server.accept()
                print("[Socket] new connection: ", conn, addr)
                # 只处理最新的连接
                if self.client is not None:
                    self.client.close()
                self.client = conn
                t = threading.Thread(target=self.recvMsg, args=(conn, addr), name="client {}".format(addr), daemon=True)
                t.start()
                
                # 只处理最早的连接
                # if self.client == None:
                #     self.client = conn
                #     t = threading.Thread(target=self.recvMsg, args=(conn, addr), name="client {}".format(addr), daemon=True)
                #     t.start()
                # else:
                #     print("already exist a connection; close!!!")
                #     conn.close()

    def recvMsg(self, client: socket.socket, address):
        print("[Socket] listen msg from ", address)
        while True:
            try:
                msg = client.recv(1024).decode()
                if len(msg):
                    print("[Socket] get msg from {}: {}".format(address, msg))
                    if self.notify != None:
                        self.notify(msg)
                else:
                    print("[Socket] client {} disconnect".format(address))
                    self.client = None
                    break
            except ConnectionResetError as error:
                print("except disconnect ", error)
                self.client = None
                break
    
    def sendMsg(self, msg):
        msg_send = msg
        if type(msg) == dict: # 如果是json,传递给javascript的应为双引号,python默认传递单引号。
            msg_send = str(msg).replace("'", '"')
        if self.client is not None:
            self.client.sendall(msg_send.encode())
            print("[Socket] send message", msg)
        else:
            print("[Socket] No any connection")

def handleMsg(msg: str):
    print("handle msg: ", msg)
    th.sendMsg({"repeat": msg})

if __name__ == "__main__":
    th = SocketServerThread(notify=handleMsg)
    th.start()
    while(True):
        pass

作者:jeady
链接:https://juejin.cn/post/7142863960593039397
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(源码,python,开发语言)