python代码实现简单的udp通信

发送方

流程:

  1. 导入包socket
  2. 创建一个套接字
  3. 收发消息(优先发送)
  4. 关闭套接字

    代码:

import socket


def main():

   ip = "127.0.0.1"  # 对方ip和端口
   port = 8888
   other_addr = (ip, port)
   byte = 1024
   udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

   while True:
       send_data = input("输入要发送的信息:").encode("utf-8")
       udp_socket.sendto(send_data, other_addr)
       """输入数据为空退出,否则进入接收状态"""
       if send_data:
           recv_data, other_addr = udp_socket.recvfrom(byte)
           print("收到来自%s的消息: %s" % (other_addr, recv_data.decode("utf-8")))
       else:
           break
   udp_socket.close() 


if __name__ == '__main__':
   main()

接收方

流程:

  1. 导入包socket
  2. 创建一个套接字
  3. 绑定信息
  4. 收发消息(优先接收)
  5. 关闭套接字
代码
import socket


def main():
    ip = ""
    port = 8888
    own_addr = (ip, port)  # 接收方端口信息
    byte = 1024
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind(own_addr)  # 绑定端口信息
    while True:
        recv_data, other_addr = udp_socket.recvfrom(byte)
        print("收到来自%s的消息: %s" % (other_addr, recv_data.decode("utf-8")))
        send_data = input("输入要发送的信息:").encode("utf-8")
        udp_socket.sendto(send_data, other_addr)
        """输入数据为空退出"""
        if send_data:
            pass
        else:
            break
    udp_socket.close()  # 关闭socket

if __name__ == '__main__':
    main()

你可能感兴趣的:(python,python,socket,udp,网络编程,入门)