1.osi七层模型
通信流程
socket(抽象层):
结合上图来看,socket在哪一层呢,我们继续看下图
socket在内的五层通讯流程:
2.TCP/UDP的区别:
TCP是以数据流的形式传输,UDP打包成数据包传输(传输速度快容易丢包,用作视频通话等)
3.paython中TCP/UDP协议下的socket对比:
代码(UDP):
-------------------------------------------------------------------------------
服务器端:
import socket
udp_server = socket.socket(type=socket.SOCK_DGRAM) #datagram
ip_port = ('127.0.0.1',8002)
udp_server.bind(ip_port)
from_client_msg,client_addr = udp_server.recvfrom(1024)
udp_server.sendto(b'gunduzi',client_addr)
print(from_client_msg,client_addr)
客户端
import socket
udp_client = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ('127.0.0.1',8002)
udp_client.sendto(b'hello',ip_port)
from_server_msg,server_addr = udp_client.recvfrom(1024)
print(from_server_msg,server_addr)
----------------------------------------------------------------------------------------------
多人通话服务器端
import socket
udp_server = socket.socket(type=socket.SOCK_DGRAM) #datagram
ip_port = ('127.0.0.1',8002)
udp_server.bind(ip_port)
while 1:
from_client_msg, client_addr = udp_server.recvfrom(1024)
print(from_client_msg.decode('utf-8'), client_addr)
to_client_msg = input('服务端说:')
udp_server.sendto(to_client_msg.encode('utf-8'), client_addr)
udp_server.close()
多人通话客户端
import socket
udp_client = socket.socket(type=socket.SOCK_DGRAM)
ip_port = ('127.0.0.1',8002)
while 1:
to_server_msg = input('客户端说')
udp_client.sendto(to_server_msg.encode('utf-8'), ip_port)
from_server_msg, server_addr = udp_client.recvfrom(1024)
print(from_server_msg.decode('utf-8'), server_addr)
udp_client.close()
------------------------------------------------------------------------------------