python中socket tcp和udp简单实现

1、socket udp发送数据

import socket

def main():
    # 创建一个udp套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # 使用套接字收发数据
    udp_socket.sendto(b"hahaha", ("192.168.2.102", 8888))

    # 关闭套接字
    udp_socket.close()


if __name__ == '__main__':
    main()

2、socket udp接收数据

import socket

def main():
    # 创建udp套接字
    socket_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 绑定端口
    socket_udp.bind(("", 8889))
    # 接收数据
    recv_data = socket_udp.recvfrom(1024)
    # 数据
    recv_msg = recv_data[0].decode("gbk")
    # 地址信息
    recv_add = recv_data[1]
    
    print(recv_msg)
    
    socket_udp.close()


if __name__ == '__main__':
    main()

3、socket tcp客户端

import socket


def main():
    # 创建tcp套接字
    tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 链接服务器
    tcp_client_socket.connect(("192.168.2.102", 8989))
    # 发送消息
    tcp_client_socket.send("你好".encode("gbk"))
    # 接收消息
    recv = tcp_client_socket.recv(1024)
    print(recv)
    # 关闭套接字
    tcp_client_socket.close()


if __name__ == '__main__':
    main()

4、socket tcp服务端

import socket


def main():
    # 创建一个tcp套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定
    tcp_server_socket.bind(("", 8889))
    # 设置为监听套接字
    tcp_server_socket.listen(128)
    while True:
        # 等待别人链接
        new_client_socket, client_addr = tcp_server_socket.accept()
        # 接收消息
        client_msg = new_client_socket.recv(1024)
        print(client_msg)
        # 回送消息
        new_client_socket.send("你好".encode("gbk"))

        # 关闭套接字
        new_client_socket.close()
    tcp_server_socket.close()

if __name__ == '__main__':
    main()

你可能感兴趣的:(Socket,python,socket,udp,网络通信,网络)