Python Network Programming Study Notes (5): Supplement to socket

Source: Internet
Author: User
Tags unpack
I have already introduced some knowledge about pythonsocket. Here I would like to add some suggestions for you to make it easier. 1. semi-open socket

Use the shutdown () function to convert two-way socket data transmission to one-way data transmission. Shutdown () requires a separate parameter, which indicates how to close the socket. Specifically: 0 indicates that future reading is prohibited; 1
Indicates that future writing is prohibited; 2 indicates that future reading and writing are prohibited.

2. timeouts control timeout

Call the settimeout () function of the socket and pass a parameter to it, indicating the timeout setting. When a socket is accessed, if nothing happens after the time specified by the parameter, a socket. timeout exception is generated.
For example, when the program runs, it will wait for data to be passed in. Use telnet to connect to port 12345 on another terminal. After the connection is successful, "connection from: *****" is displayed. If no input is made from the terminal within five seconds
The system prompts that the connection times out and exits.

The Code is as follows:

The Code is as follows:


#-*-Coding: cp936 -*-
# Tcp response Server
Import socket, traceback
Host =''
Port = 12345
S = socket. socket (socket. AF_INET, socket. SOCK_STREAM)
S. setsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1)
S. bind (host, port ))
S. listen (1)

While 1:
Try:
Clientsock, clientaddr = s. accept ()
Except t KeyboardInterrupt:
Raise
Except t:
Traceback. print_exc ()
Continue
Clientsock. settimeout (5)
Try:
Print "connection from:", clientsock. getpeername ()
While 1:
Data = clientsock. recv (4096)
If not len (data ):
Break
Clientsock. sendall (data)
Clientsock. sendall ("\ nI get it! \ N ")
# T = raw_input ('input the word :')
# Clientsock. sendall (t)
Except T (KeyboardInterrupt, SystemExit ):
Raise
Failed t socket. timeout:
Print 'Connection timeout'
Pass
Except t:
Traceback. print_exc ()

Try:
Clientsock. close ()
Except t KeyboardInterrupt:
Raise
Except t:
Traceback. print_exc ()

3. Understand the network byte sequence

Different platforms have different binary data encoding methods. To solve this problem, a standard binary data representation is called the network byte sequence. Before sending a binary integer, the integer is
To the byte sequence of the network. After receiving the data, the receiver first converts the network bytes to the local representation cost.
The python struct module supports data conversion between python and binary data.
There are two basic formats:
H: Applicable to 16-digit integers
I: Applicable to 32-bit Integers
The exclamation point indicates that the struct module uses the network byte sequence for encoding and decoding. Other formats are shown in the following table:

Character

Byte order

Size and alignment

@

Native

NativeEnough4Bytes

=

Native

StandardBy the number of original bytes

<

Little-endian

StandardBy the number of original bytes

>

Big-endian

StandardBy the number of original bytes

!

Network (= big-endian)

StandardBy the number of original bytes


Common statements:

Struct. pack (fmt, v1, v2,...) converts v1 and v2 according to the parameter format. The fmt parameter is a format character.
String, here mainly! I. V1, v2,... indicates the python value to be converted.
Struct. unpack (fmt, string) is the opposite of pack.
For example:

>>> Import struct
>>> A = 20
>>> Str = struct. pack ("! I ",)
>>> Print repr (str)
'\ X00 \ x00 \ x00 \ x14'
>>> Print struct. unpack ("! I ", str)
(20 ,)

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.