Python基础(五)--- Python TCP Socket,Python UDP Socket

一、Python TCP Socket
-------------------------------------------------------
    1.Server端
        # -*- encoding=utf-8 -*-

        import socket

        # SOCK_STREAM表示 TCP协议,创建一个socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # 绑定地址和端口
        sock.bind(("localhost",8888));

        # 开启监听[0  -- 拒绝连接的个数]
        sock.listen(0)

        print("开始监听...")
        buf = 1024
        while True:
            # 接收连接,阻塞的
            (clientSock,clientAddr) = sock.accept()
            print("有连接了" + str(clientAddr))
            while True:
                # 接收的client的数据[字节数组]
                data = clientSock.recv(buf);
                s = int.from_bytes(data,byteorder='little');
                print("client say: %s" %(s))
                # 发送消息给客户端
                clientSock.send(b"received msg");

    2.Client端
        # -*- encoding=utf-8 -*-

        import socket
        import time

        #开启套接字
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM);

        # 建立连接
        sock.connect(("localhost",8888));

        index = 0;
        while True:
            b = index.to_bytes(4,byteorder="little");
            sock.send(b)
            index += 1;
            time.sleep(2)

            # 接收服务器发送来的消息
            recv=sock.recv(1024)
            print('[tcpServer said]: %s' % recv)


二、Python UDP Socket
---------------------------------------------------
    1.Sender方
        # -*- encoding=utf-8 -*-

        import socket

        # SOCK_DGRAM表示 UDP协议,创建一个socket
        sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # 绑定地址和端口[接收数据的端口]
        sender.bind(("localhost",9999));
        print("启动了UDP发送者...")

        buf = 1024
        index = 0;
        while True:
            # 发送数据
            msg = "hello:" + str(index);
            msgBytes = msg.encode("utf-8");
            # 向localhost:8888发送数据
            sender.sendto(msgBytes,("localhost",8888));
            print("发送了" + msg)
            import time
            time.sleep(2)
            index +=1

    2.Receiver方
        # -*- encoding=utf-8 -*-

        import socket

        # SOCK_DGRAM表示 UDP协议,创建一个socket
        receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # 绑定地址和端口
        receiver.bind(("localhost",8888));
        print("启动了UDP接收者...")
        buf = 1024
        while True:
            # 接收数据,永不停止,一直接收
            (data,clientAddr) = receiver.recvfrom(buf)
            mag = bytes.decode(data);
            print("接收到来自" + str(clientAddr[1]) + "的数据:" + mag);













猜你喜欢

转载自blog.csdn.net/xcvbxv01/article/details/83997682