socket又称套接字
使用server实现循环通信 代码如下
import socket server = socket.socket() server.bind(('192.168.16.33',8000)) server.listen(5) while 1: coon,addr = server.accept() while 1: ret = coon.recv(1024).decode('utf-8') print(ret) msg = input('内容:').encode('utf-8') coon.send(msg) coon.close() server.close()
客户端如下
import socket client = socket.socket() client.connect(('192.168.16.33',8000)) while 1: msg = input('>>>') client.send(msg.encode('utf-8')) ret = client.recv(1024).decode('utf-8') print(ret) client.close()
使用socketserver可以实现并发通信
import socketserver class MY_server(socketserver.BaseRequestHandler): def handle(self): ret = self.request.recv(1024).decode('utf-8') print(ret) if __name__ == '__main__': ip = ('127.0.0.1',8000) server = socketserver.ThreadingTCPServer(ip,MY_server)
使用socket实现通信效果很容易造成黏包现象
产生黏包现象需要用struct和josn序列化的方式来解决,
import struct import subprocess import socket server = socket.socket() server.bind(('127.0.0.1',8000)) server.listen(5) coon,addr = server.accept() cmd = coon.recv(1024).decode('utf-8') print(cmd) obj = subprocess.Popen(cmd,shell= True,stderr=subprocess.PIPE,stdout=subprocess.PIPE) right_obj = obj.stdout.read() error_obj = obj.stderr.read() date_beyes = len(right_obj + error_obj) print(date_beyes) struct_date_beyes = struct.pack('i',date_beyes) print(struct_date_beyes) coon.send(struct_date_beyes) coon.send(right_obj +error_obj)
import socket import struct client = socket.socket() client.connect(('127.0.0.1',8000)) cmd = input('>>>').encode('utf-8') client.send(cmd) beyes_struct_len = client.recv(4) print(beyes_struct_len) beyes_struct_ = struct.unpack('i',beyes_struct_len)[0] date = b'' while len(date) < beyes_struct_: form_date = client.recv(1024) date += form_date print(date.decode('gbk'))
上图是解决黏包现象的客户端和服务端代码