Note 5: some additions to sockets

  • 2020-04-02 13:43:48
  • OfStack

1. Semi-open socket

Use the shutdown() function to change the socket two-way data transfer to one-way data transfer. Shutdown () requires a separate parameter that indicates how to close the socket. Specifically: 0 means prohibit future reading; 1
Prohibit future writing; 2 means future reading and writing are forbidden.

2. Timeouts controls timeouts

Call the socket's settimeout() function, passing it an argument indicating the timeout setting. When accessing a socket, if nothing happens after the parameter setting time, a socket.timeout exception is generated.
For example, when a program runs, it waits for data to come in. At the other terminal, connect to port 12345 using Telnet. After a successful connection, the display "connection from: ****", if this time within 5 seconds, the terminal did not enter, system
The union will prompt the connection to exit with a timeout.

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 KeyboardInterrupt:
        raise
    except:
        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 (KeyboardInterrupt,SystemExit):
        raise
    except socket.timeout:
        print ' Connection timeout '
        pass
    except:
        traceback.print_exc()
    try:
        clientsock.close()
    except KeyboardInterrupt:
        raise
    except:
        traceback.print_exc()

3. Understand network byte order

Different platforms have different ways of encoding binary data, and to address this, a standard binary representation of data is called network byte order. Before sending a binary integer, the integer is first sent by
Converts to network byte order. Upon receipt, the receiver converts the network byte order into a local representation before using the data.
Python's struct module provides support for converting data between python and binary data.
There are two main basic formats:
H: for 16-bit integers
I: for 32-bit integers
An exclamation point indicates that the struct module USES network byte order to encode and decode. Other formats are shown in the following table:

Character

Byte   The order

The Size   The and   alignment

@

native

native                         That's four bytes

=

native

standard                 In bytes

<

Little endian -

standard                 In bytes

>

Big endian -

standard               In bytes

!

The network   (=   Big endian)

standard               In bytes


Common statements:

Struct. Pack (FMT, v1, v2,...). Convert v1 and v2 into parameter format. The parameter FMT is the format character
String, here is mainly! I. V1, v2,... Represents the python value to be converted.
Struct. unpack(FMT,string) is the opposite of pack.
Such as:

> > > The import struct
> > > A = 20
> > > STR = struct. Pack (! "" I ", a)
> > > Print repr (STR)
'/ x00 / x00 \ x00 \ x14'
> > > Print struct. Unpack (! "" I ", STR)
(20)


Related articles: