Python Learning Notes (socket module)

Source: Internet
Author: User

1, the socket module used to be divided into the server and the client, the server to receive and process the request, and then return the request data back to the client, the client to read data, close the connection, and finally end the interaction

2, the service side socket module use steps:

1 ImportSocket2 3Phone=Socket.socket (Socket.af_inet,socket. SOCK_STREAM)4Phone.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1)#5Phone.bind (('127.0.0.1', 8080))#bind (host, port number) to socket6 7Phone.listen (5)#Start TCP snooping8 9Conn,client_addr=phone.accept ()#passive acceptance of TCP client connections, (blocking) waiting for a connection to arriveTen  OneCLIENT_DATA=CONN.RECV (1024)#receive TCP Data max 1024 bytes AConn.send (Client_data.upper ())#Sending TCP Data -  -  theConn.close ()#Close Tcpl Connection -  -Phone.close ()#Close Socket
View Code

3, the client socket module use steps:

1 ImportSocket2 3Phone=Socket.socket (Socket.af_inet,socket. SOCK_STREAM)4Phone.connect (('127.0.0.1', 8080))#connecting the ip+port of the service side5 6 7Msg=input ('>>:'). Strip ()8 9Phone.send (Msg.encode ('Utf-8'))#sending information to the serverTenSERVER_DATA=PHONE.RECV (1024)#Receiving service-side information One  A  -Phone.close ()#Close Connection
View Code

4, the socket module is based on TCP or UDP protocol implementation, because the TCP protocol is streaming data, TCP protocol-based socket will appear sticky packet phenomenon, to solve the sticky packet phenomenon requires the use of a struct module.

The purpose of a struct module: to convert a type, such as a number, into a fixed-length bytes

How to use: A=struct.pack (' I ', 123123123123) # replace 123123123123 with 4 bytes length;

Stauct.unpack (' I ', a) [0] #提取123123123123

Verbose type conversion

Handling Sticky Pack Issues:

We can make a dictionary of the header, the dictionary contains the details of the real data to be sent, then JSON serialization, and then use struck to package the serialized length of the data into 4 bytes (4 of them enough)

When sending: header length first

Re-encode the header contents and send

Finally send the real content

Received: Initiator header length, removed with struct

The header content is charged according to the length taken, then decoded and deserialized

Extract the details of the data to be fetched from the deserialized results and then fetch the actual data content

1 ImportSocket,struct,json2 Importsubprocess3Phone=Socket.socket (Socket.af_inet,socket. SOCK_STREAM)4Phone.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1)#That 's it, in front of BIND plus5 6Phone.bind (('127.0.0.1', 8080))7 8Phone.listen (5)9 Ten  whileTrue: OneConn,addr=phone.accept () A      whileTrue: -CMD=CONN.RECV (1024) -         if  notCmd: Break the         Print('cmd:%s'%cmd) -  -Res=subprocess. Popen (Cmd.decode ('Utf-8'), -Shell=True, +stdout=subprocess. PIPE, -Stderr=subprocess. PIPE) +Err=Res.stderr.read () A         Print(ERR) at         ifERR: -back_msg=Err -         Else: -back_msg=Res.stdout.read () -  -  inConn.send (Struct.pack ('I', Len (back_msg)))#the length of first hair back_msg -Conn.sendall (BACK_MSG)#in the hair of the real content to  + conn.close () -  theServer (self-customizing header)
Service-side code
1 #_*_coding:utf-8_*_2 Importsocket,time,struct3 4s=Socket.socket (Socket.af_inet,socket. SOCK_STREAM)5RES=S.CONNECT_EX (('127.0.0.1', 8080))6 7  whileTrue:8Msg=input ('>>:'). Strip ()9     ifLen (msg) = = 0:ContinueTen     ifmsg = ='quit': Break One  AS.send (Msg.encode ('Utf-8')) -  -  the  -L=S.RECV (4) -X=struct.unpack ('I', L) [0] -     Print(Type (x), x) +     #Print (Struct.unpack (' I ', L)) -r_s=0 +Data=b"' A      whiler_s <x: atR_D=S.RECV (1024) -data+=R_d -r_s+=Len (r_d) -  -     #Print (Data.decode (' Utf-8 ')) -     Print(Data.decode ('GBK'))#Windows default GBK encoding in  -Client (self-customizing header)
Client Code

  

Python Learning Notes (socket module)

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.