Python Socket programming details, pythonsocket
When using Python for socket programming, you need to use the blocking (default) method to read data streams. At this time, you need to process the data at the end of each time, which is too troublesome. And no good encapsulation is found on the Internet, so I wrote a simple encapsulation myself.
Encapsulation
1. Each request from the client sends a SocketRequest object, which encapsulates the specific data. json is used here. An end sign (EOF = '0x00') is automatically added for the data to be sent ').
2. When the server receives data, it generates the complete data based on the terminator ID and unpacks the data into a SocketRequest object.
3. The server generates a SocketResponse object based on the content of SocketRequest. Here, a SimpleRequestHandler class is used for processing. In this example, no processing is performed and the result is returned as is.
4. the server sends SocketResponse to the client. The package also needs to be encapsulated, and an ending sign (EOF = '0x00') will be automatically added ').
5. When receiving data, the customer generates the complete data based on the terminator identifier, unpacks the data into a SocketResponse object, and then returns it.
Encapsulation class
Sockets. py
#!/usr/bin/env python# -*- coding: utf-8 -*-import socketimport pickleimport threadPORT = 12345EOF = '0x00'class SocketServer(object): def __init__(self, port=None): self.port = port def startup(self): sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_server.bind(('0.0.0.0', self.port)) sock_server.listen(0) while True: sock, address = sock_server.accept() thread.start_new_thread(self.__invoke, (sock, address)) def shutdown(self): pass def __invoke(self, sock, address): try: full_data = '' while True: data = sock.recv(1024) if data is None: return full_data += data if full_data.endswith(EOF): full_data = full_data[0:len(full_data) - len(EOF)] request = pickle.loads(full_data) response = SimpleRequestHandler().handle(request) sock.sendall(pickle.dumps(response) + EOF) return except Exception as e: print e finally: sock.close()class SocketClient(object): def __init__(self, host, port): self.host = host self.port = port def execute(self, request): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((self.host, self.port)) try: sock.sendall(pickle.dumps(request) + EOF) full_data = '' while True: data = sock.recv(1024) if data: full_data += data if full_data.endswith(EOF): full_data = full_data[0:len(full_data) - len(EOF)] response = pickle.loads(full_data) return response else: return None except Exception as e: print e return None finally: sock.close()class SocketRequest(object): def __init__(self, data): self.data = data def __repr__(self): return repr(self.__dict__)class SocketResponse(object): def __init__(self, data): self.data = data def __repr__(self): return repr(self.__dict__)class SimpleRequestHandler(object): def __init__(self): pass def __repr__(self): return repr(self.__dict__) def handle(self, request): return SocketResponse(request.data)
Test
Socket_server.py
#!/usr/bin/env python# -*- coding: utf-8 -*-from agent.sockets import *ss = SocketServer(PORT)ss.startup()
Socket_client.py
#!/usr/bin/env python# -*- coding: utf-8 -*-import picklefrom agent.sockets import *sc = SocketClient('localhost', PORT)request = SocketRequest('abc')response = sc.execute(request)print requestprint response
Run the test
First, run socket_server.py
Then, run socket_client.py
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.