UDP协议的服务端和客户端:
##udp_服务端
import socket
udp_server = socket.socket(type=socket.SOCK_DGRAM)#选择udp协议
ip_port = ('192.168.15.75',8001)
udp_server.bind(ip_port)
#收消息
from_client_msg,client_addr = udp_server.recvfrom(1024)
print(from_client_msg.decode("utf-8"))#你好啊
print(client_addr)#('192.168.15.75', 57486)
#发消息
msg=("哈哈哈").encode("utf-8")
udp_server.sendto(msg,client_addr)
udp_server.close()
#udp 服务端
#udp客户端
import socket
udp_client = socket.socket(type=socket.SOCK_DGRAM)#选择udp协议
server_ip_port = ('192.168.15.75',8001)
#发消息
msg="你好啊".encode("utf-8")
udp_client.sendto(msg,server_ip_port)#直接发消息给服务端
#收消息
from_server_msg,server_addr = udp_client.recvfrom(1024)#收消息
print(from_server_msg.decode("utf-8"))#哈哈哈
print(server_addr)#('192.168.15.75', 8001)
udp_client.close()
#udp 客户端
TCP协议的服务端和客户端:
##tcp_服务端
import socket
tcp_server = socket.socket()#默认选择tcp协议
ip_port = ('192.168.15.75',8001)
tcp_server.bind(ip_port)
tcp_server.listen()
conn,client_addr = tcp_server.accept()
#收消息
from_server_msg = conn.recv(1024)
print(from_server_msg.decode("utf-8"))#你好啊
print(client_addr)#('192.168.15.75', 13618)
#发消息
msg=("哈哈哈").encode("utf-8")
conn.send(msg)
tcp_server.close()
#TCP服务端
#TCP客户端
import socket
tcp_client = socket.socket()#默认选择tcp协议
server_ip_port = ('192.168.15.75',8001)
tcp_client.connect(server_ip_port)
#发消息
msg="你好啊".encode("utf-8")
tcp_client.send(msg)
#收消息
from_server_msg= tcp_client.recv(1024)#收消息
print(from_server_msg.decode("utf-8"))#哈哈哈
tcp_client.close()
#TCP客户端