TCP和UDP的socket通信
Python版本:3.9.6
ide:PyCharm 2021.1.3
????????前几天项目上在测试udp和tcp数据的转发,需要验证转发后的数据格式,写了demo检查数据,简单实现了客户端和服务端,如下:
TCP服务端:
# TCP服务端
import socket
address = ('', 10016)
# 创建套接字:socket.AF_INET-IPv4套接字类型;socket.SOCK_STREAM-数据流,TCP
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 防止重启后端口被占用
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑定的IP与端口
server.bind(address)
# 监听一个请求
server.listen(1)
print('waiting for connection...')
conn, addr = server.accept()
print('connected by', addr, '...')
while True:
data = input('input your message:')
conn.send(data.encode('gbk'))
conn.close()
TCP客户端:
# TCP客户端
import socket
address = ('192.168.121.206', 10016)
# 创建套接字:socket.AF_INET-IPv4套接字类型;socket.SOCK_STREAM-数据流,TCP
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('try to connect to', address, '...')
while True:
try:
client.connect(address)
except socket.error as msg:
print(msg, 'retry...')
else:
print('connected to', address, '...')
break
while True:
data = client.recv(1024)
if data:
print('the received message is:', data.decode('gbk'))
client.close()
UDP服务端:
# UDP服务端
import socket
address = ('192.168.121.206', 10015)
# 创建套接字:socket.AF_INET-IPv4套接字类型;socket.SOCK_DGRAM-数据包,UDP
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
data = input('input your message:')
# 对方的IP和Port
server.sendto(data.encode('gbk'), address)
# 退出套接字
server.close()
UDP客户端:
# UDP客户端
import socket
# 本地IP和Port
address = ('', 10015)
# 创建套接字:socket.AF_INET-IPv4套接字类型;socket.SOCK_DGRAM-数据包,UDP
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 防止重启后端口被占用
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
client.bind(address)
while True:
data, addr = client.recvfrom(1024)
if not data:
print("data null...")
else:
print('received:', data.decode("gbk"), 'from', addr)
# 退出套接字
client.close()
|