UDP network

How to view the port number?

  • -an view the port number used by the program using netstat
  • lsof -i [tcp / udp]: 2425 View application corresponding to the port number
 

UDP advantages and disadvantages

advantage:

  • Transmission speed
  • No connection, small resource overhead

Disadvantages:

  • Data transmission is not reliable, easy to lose packets
  • No flow control, when the other person did not receive the data, the sender has been sending data can result in data buffer is full, the computer appears stuck, all the recipient needs to receive timely data.

send data

import socket

# 1. 创建udp套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 2. 准备接收方的地址
# '192.168.1.103'表示目的ip地址
# 8080表示目的端口 dest_addr = ('192.168.1.103', 8080) # 注意 是元组,ip是字符串,端口是数字 # 3. 从键盘获取数据 send_data = input("请输入要发送的数据:") # 4. 发送数据到指定的电脑上的指定程序中 udp_socket.sendto(send_data.encode('utf-8'), dest_addr) # 5. 关闭套接字 udp_socket.close()

Send and receive data

import socket

# 1. 创建udp套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 2. 准备接收方的地址
dest_addr = ('192.168.236.129', 8080) # 3. 从键盘获取数据 send_data = input("请输入要发送的数据:") # 4. 发送数据到指定的电脑上 udp_socket.sendto(send_data.encode('utf-8'), dest_addr) # 5. 等待接收对方发送的数据 recv_data = udp_socket.recvfrom(1024) # 1024表示本次接收的最大字节数 # 6. 显示对方发送的数据 # 接收到的数据recv_data是一个元组 # 第1个元素是对方发送的数据 # 第2个元素是对方的ip和端口 print(recv_data[0].decode('gbk')) print(recv_data[1]) # 7. 关闭套接字 udp_socket.close()

Binding port number

#coding=utf-8

from socket import *

# 1. 创建套接字
udp_socket = socket(AF_INET, SOCK_DGRAM)

# 2. 绑定本地的相关信息,如果一个网络程序不绑定,则系统会随机分配 local_addr = ('', 7788) # ip地址和端口号,ip一般不用写,表示本机的任何一个ip udp_socket.bind(local_addr) # 3. 等待接收对方发送的数据 recv_data = udp_socket.recvfrom(1024) # 1024表示本次接收的最大字节数 # 4. 显示接收到的数据 print(recv_data[0].decode('gbk')) # 5. 关闭套接字 udp_socket.close()

Send broadcast

import socket
# 创建udpsocket
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 设置socket的选项,允许发送广播消息
    udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, True)
    # 发送广播消息
    udp_socket.sendto("大家好,我叫小郭同学,多多关照!".encode("gbk"), ("255.255.255.255", 9090)) # 关闭socket udp_socket.close()
- encoding and decoding
encode () decode () decodes
bytes.decode(encoding="utf-8", errors="strict")
strict: If the codec is unsuccessful crash
ignore: If the codec is unsuccessful program does not crash

 

import socket

# 1. 创建udp套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 2. 准备接收方的地址
# '192.168.1.103'表示目的ip地址
# 8080表示目的端口 dest_addr = ('192.168.1.103', 8080) # 注意 是元组,ip是字符串,端口是数字 # 3. 从键盘获取数据 send_data = input("请输入要发送的数据:") # 4. 发送数据到指定的电脑上的指定程序中 udp_socket.sendto(send_data.encode('utf-8'), dest_addr) # 5. 关闭套接字 udp_socket.close()

 

Guess you like

Origin www.cnblogs.com/lab-zj/p/12166229.html