0. 说明
Python Socket 编程
1. TCP 协议
[TCP Server]
通过 netstat -ano 查看端口是否开启
# -*-coding:utf-8-*-""" TCP 协议的 Socket 编程,Server 端 Server 端绑定到指定地址,监听特定的端口,接受发来的连接请求"""import threadingimport socketimport timeclass CommThread(threading.Thread): def run(self): while True: # 接受数据 data = sock.recv(4096) print("收到了%s = %s" % (str(self.addr), str(data)), ) def __init__(self, sock, addr): threading.Thread.__init__(self) self.sock = sock self.addr = addr# 创建服务器套接字,绑定端口ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)ss.bind(("127.0.0.1", 8888))ss.listen(0)while True: sock, addr = ss.accept() CommThread(sock, addr).start() print("%s链接进来\r\n" % (str(addr)), ) time.sleep(1)
[TCP Client]
# -*-coding:utf-8-*-""" TCP 协议的 Socket 编程,Client 端"""import threadingimport socketimport time# 创建服务器套接字,绑定端口sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect(("127.0.0.1" , 8888))i = 1while True: str = "tom%d\r\n" % (i) print ("client : " + str), sock.send(bytes(str,'utf-8')) time.sleep(1) i += 1
2. UDP 协议
[UDP Server]
# -*-coding:utf-8-*-""" UDP 协议的 Socket 编程,Server 端"""import socket# 创建 UDP 接收方sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)sock.bind(("192.168.13.6", 9999))i = 1while True: data = sock.recv(4096) print(str(data))
[UDP Client]
# -*-coding:utf-8-*-""" UDP 协议的 Socket 编程,Client 端"""import socketimport time# 创建 UDP 发送方sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)sock.bind(("192.168.13.6", 8888))i = 1while True: sock.sendto(bytes(("tom" + str(i)),'utf-8'), ("192.168.13.255", 9999)) i += 1 time.sleep(1)