Python Socket Programming

Source: Internet
Author: User

Python Socket Programming

When using Python for socket programming, It is cumbersome to use the blocking (default) way to read the data stream at the end of each process. And did not find a good package on the internet, so I wrote a simple package.

Packaging ideas
1. Each request of the client sends a socketrequest object, which encapsulates the specific data, using Json. For the data to be sent, a terminator identifier (EOF = ' 0x00 ') is automatically added.
2. When the server receives the data, the complete data is generated according to the Terminator identifier and unpacked into the Socketrequest Object.
3. The server-side generates Socketresponse objects based on Socketrequest content, which is handled using a Simplerequesthandler class, in which case no processing is done and returned as is.
4. Server-side sends Socketresponse to the Client. It also requires a wrapper for the package, which automatically adds a terminator identifier (EOF = ' 0x00 ').
5. When the customer receives the data, the complete data is generated according to the Terminator identifier, and the Socketresponse object is unpacked and Returned.

Encapsulation Class sockets.py
#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketImportPickleImportThreadport =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 (1024x768)ifData is None:returnFull_data + = DataifFull_data.endswith (EOF): full_data = full_data[0: Len (full_data)-len (EOF)] request = pickle.loads (full_data) response = Simplereque Sthandler (). handle (request) sock.sendall (pickle.dumps (response) + EOF)return        exceptException asE:PrintEfinally: 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 (1024x768)ifData:full_data + = DataifFull_data.endswith (EOF): full_data = full_data[0: Len (full_data)-len (EOF)] response = pickle.loads (full_data)returnResponseElse:return None        exceptException asE:PrintEreturn None        finally: Sock.close () class socketrequest(object):     def __init__(self, data):Self.data = Data def __repr__(self):        returnRepr (self.__dict__) class socketresponse(object):     def __init__(self, data):Self.data = Data def __repr__(self):        returnRepr (self.__dict__) class simplerequesthandler(object):     def __init__(self):        Pass     def __repr__(self):        returnRepr (self.__dict__) def handle(self, request):        returnSocketresponse (request.data)
Test socket_server.py
#!/usr/bin/env python# -*- coding: utf-8 -*-fromimport *ss = SocketServer(PORT)ss.startup()
socket_client.py
#!/usr/bin/env python# -*- coding: utf-8 -*-import picklefromimport *sc = SocketClient(‘localhost‘, PORT)request = SocketRequest(‘abc‘)response = sc.execute(request)print requestprint response
Run Tests
首先,运行 socket_server.py然后,运行 socket_client.py

Python Socket Programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.