- tcp套接字
被动端(服务器) 主动端(客户端)
s = socket() s = socket()
s.bind() s.bind()---->可省略
s.listen() s.connect()
s.accept()
s.recv() / s.send() s.recv() / s.send()
s.close() s.close()
- 创建服务端
import socket, time from multiprocessing import Process def fun(sd): for i in range(3): sd.send(b'ok!!!') time.sleep(1) sd.close() if __name__ == '__main__': s = socket.socket() s.bind(('192.168.5.68', 6688)) s.listen(20) while True: newsd, raddr = s.accept() print('recv client ip:{}, port:{}'.format(*raddr)) pro = Process(target=fun, args=(newsd, )) pro.start()
- 创建客户端
import socket if __name__ == '__main__': s = socket.socket() # bind() s.connect(('192.168.5.68', 8888)) ''' while True: rcvdata = s.recv(1024) if rcvdata == b'': break print(rcvdata.decode('utf-8')) s.close() ''' s.send(b'hello')
- 多线程并发、多进程并发
- 服务端
import socketserver as ss import time class MyRequest(ss.BaseRequestHandler): def handle(self): '''服务端的工作''' # self.request是已连接套接字 self.socket监听套接字 data = self.request.recv(1024) print('客户端地址ip:{}, port:{}'.format(*self.client_address)) print(data) time.sleep(3) if __name__ == '__main__': with ss.ThreadingTCPServer(('192.168.5.68', 8888), MyRequest) as server: server.serve_forever()
- 客户端
import socket if __name__ == '__main__': sd = socket.socket(type=socket.SOCK_DGRAM) sd.sendto(b'hello world', ('192.168.5.129', 9988)) sd.close()
- udp套接字
server client
s=socket.socket() s = socket.socket()
s.bind() # s.bind()
s.sendto()
s.recvfrom()
s.close() s.close()
import socket if __name__ == '__main__': sd = socket.socket(type=socket.SOCK_DGRAM) sd.bind(('192.168.5.68', 9999)) while True: data, clientaddr = sd.recvfrom(1024) print('from ip:{}, port:{}'.format(*clientaddr)) print(data.decode('utf-8')
# ForkingUDPServer只能应用于unix操作系统 from socketserver import ForkingUDPServer, BaseRequestHandler import time class MyUdpRequest(BaseRequestHandler): def handle(self): # self.request是一个元祖,包含两个成员,分别是数据,以及套接字对象 data = self.request[0] sd = self.request[1] # socket print('from ip:{}, port:{},recv:{}'.format(*self.client_address, data.decode())) time.sleep(10) if __name__ == '__main__': with ForkingUDPServer(('192.168.5.68', 9988), MyUdpRequest) as server: server.serve_forever()
- 熟悉掌握三次握手,四次挥手: