Python3 网络编程(使用Socket实现TCP、UDP通信)
TCP通信
TCP_服务端
1 import socket as s
2
3 tcp = s.socket(s.AF_INET,s.SOCK_STREAM)
4 tcp.bind(('127.0.0.1', 6666))
5 tcp.listen(5)
6 while True:
7 # 建立客户端连接
8 clientsocket,addr = tcp.accept()
9 print("连接地址: %s" % str(addr))
10 msg = '欢迎访问{}!'.format(tcp.getsockname())+ "\r\n"
11 clientsocket.send(msg.encode('utf-8'))
12 clientsocket.close()
TCP_客户端
import socket as s
tcp = s.socket(s.AF_INET,s.SOCK_STREAM)
tcp.connect(('127.0.0.1', 6666))
msg = tcp.recv(1024)
tcp.close()
print (msg.decode('utf-8'))
UDP通信
UDP_服务端
import socket BUFSIZE = 1024 ip_port = ('127.0.0.1', 9999) server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # udp协议 server.bind(ip_port) while True: data,client_addr = server.recvfrom(BUFSIZE) print('client地址:', client_addr,'server收到的数据:', data.decode("UTF-8")) server.sendto(data,client_addr) server.close()
UDP_客户端
import socket BUFSIZE = 1024 client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: msg = input(">>").strip() ip_port = ('127.0.0.1', 9999) client.sendto(msg.encode('utf-8'),ip_port) data,server_addr = client.recvfrom(BUFSIZE) print(server_addr,'服务端收到: ',data.decode("UTF-8")) client.close()