Python module--socket (for simple c/S architecture end-of-communication operation CMD)

Source: Internet
Author: User

# service-side code
#!/usr/bin/env python#-*-coding:utf-8-*-__author__="Loki"ImportSocketImportSubprocessserver=Socket.socket (socket.af_inet, socket. SOCK_STREAM) server.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR,1) Ip_port= ('127.0.0.1', 8011) Server.bind (ip_port) Server.listen (5)#Link Loops while1: Print('Waiting ...') conn, addr=server.accept ()Print('-->conn:', conn)Print('-->addr:', addr)Print('Got it ...') while1: Try: cmd= CONN.RECV (1024) Res= subprocess. Popen (Cmd.decode ('Utf-8'), Shell=True, stdout=subprocess. PIPE, stderr=subprocess. PIPE) Conn.send (Res.stdout.read ()) Conn.send (Res.stderr.read () )exceptException: Breakconn.close ()#server.close ()

Client
#!/usr/bin/env python#-*-coding:utf-8-*-__author__="Loki"Importsocketclient=Socket.socket (socket.af_inet, socket. SOCK_STREAM) Ip_port= ('127.0.0.1', 8011) Client.connect (ip_port)#Communication Cycle while1: #Send Messagecmd = input ('>>:'). Strip ()if notcmd:Continueclient.send (bytes (cmd, encoding='Utf-8')) #Receive Messagedata = CLIENT.RECV (8196) Print(Data.decode ('GBK'))#client.close ()

The above code is based on the TCP-streaming mode of C/s control, note that the encoding of Linux for Utf-8,windows for GBK

Known Bugs:

1. There may be a sticky packet problem when the received information is greater than 8196 (or the value you define yourself)

2. Execute executable program or CMD command that requires interaction, client will be down and need to re-open clients

3. If it is used as a pure PY script also need to make sys.platform system judgment, if it is win using encoding Gbk,linux encoding Utf-8

4. The above code is only for learning reference use

Python module--socket (for simple c/S architecture end-of-communication operation CMD)

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.