udp:
优点 无连接、传输速度快、资源占用率低。
缺点 不安全、可能会丢包。
小案例 用Python实现udp收发数据:
#使用udp实现收发数据
from socket import *
udpSocket = socket(AF_INET,SOCK_DGRAM)
udpSocket.bind(('',9999))
recvdata,ip = udpSocket.recvfrom(1024)
udpSocket.sendto(recvdata,ip)
print(recvdata.decode())
tcp:
优点 面向连接、稳定可靠。
缺点 传输速度相对于udp慢、资源占用率高。
小案例 用python实现TCP客户端下载服务端文件:
#服务端
import socket
import os
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.bind(('',6666))
server_socket.listen(128)
def main():
while 1:
client_socket,addr = server_socket.accept()
print("接受到一个客户端请求")
file_name = client_socket.recv(1024).decode()
print(file_name)
if os.path.exists(file_name):
client_socket.send('success'.encode())
file_read = open(file_name, 'rb')
client_socket.send(file_read.read())
else:
client_socket.send('error'.encode())
client_socket.close()
if __name__ = "__main__":
main()
#客户端
import socket
def main():
client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip = input("请输入服务器ip:")
port = int(input("请输入端口:"))
client_socket.connect((ip,port))
file_name = input("请输入要下载的文件名:")
client_socket.send(file_name.encode())
state = client_socket.recv(1024)
if state.decode() == "success":
file_write = open('d_' + file_name, 'wb')
while 1:
data = client_socket.recv(2048)
if len(data) == 0:
break
file_write.write(data)
file_write.close()
client_socket.close()
print("文件下载完成!")
else:
print("文件下载失败!")
client_socket.close()
if __name__ == "__main__":
main()