UDP
UDP is connectionless-oriented protocol, UDP data including destination port number and source port number information, as needed for the communication connection, broadcast transmission can be realized. Limit the size of UDP data transmission, each transmitted data packets must be defined within the 64KB. UDP is an unreliable protocol, data packets sent by the sender is not necessarily in the same order arrives at the receiving side.
udp communication model, prior to the start of communication, no need to establish relevant links, only you need to send data to, like life, "write."
Client:
from socket import socket,AF_INET,SOCK_DGRAM
# 创建套接字,SOCK_DGRAM使用udp协议
udp = socket(AF_INET, SOCK_DGRAM)
# 目的端口和ip
ip = "127.0.0.1"
port = 8080
# 循环从键盘输入发送消息
while True:
data = input("请输入发送的数据:")
udp.sendto(data.encode("utf-8"), (ip, port))
Server:
from socket import socket, AF_INET, SOCK_DGRAM
udp = socket(AF_INET, SOCK_DGRAM)
# 绑定端口,服务端必须要绑定端口
udp.bind(("", 8080))
while True:
# 接受数据,每次接受1024字节
recvData = udp.recvfrom(1024)
# 拆包
data, info = recvData
# 打印
print("[%s]:%s" % (info, data.decode("utf-8")))
TCP
udp communication model, prior to the start of communication, we must first establish relevant links in order to send data, like life, "Call."
Client:
from socket import socket,AF_INET,SOCK_STREAM
# 创建套接字,SOCK_STREAM表示使用tcp协议
clientSocket = socket(AF_INET,SOCK_STREAM)
# 连接服务器
clientSocket.connect(("127.0.0.1",8080))
# 发送数据
while True:
s = input("请输入要发送的数据:")
clientSocket.send(s.encode("utf-8"))
Server:
from socket import socket, AF_INET, SOCK_STREAM
tcp = socket(AF_INET, SOCK_STREAM)
# 绑定端口
tcp.bind(("", 8080))
# listen的参数代表可建立socket连接的最大个数 windows,mac 此连接参数有效 Linux 此连接参数无效,默认最大
tcp.listen()
# 有新的客户端连接时,
# clientSocket表示一个新的套接字
# clientInfo 表示新客户端的ip及端口号
while True:
clientSocket, clientInfo = tcp.accept()
try:
while True:
recvData = clientSocket.recv(1024)
# 如果接受的的数据为空就退出
if not recvData:
break
print("%s:%s" % (str(clientInfo), recvData.decode("utf-8")))
finally:
clientSocket.close()