Python Basics: Network Programming Socket Basics

Source: Internet
Author: User

Socket is also called socket, is the encapsulation of a variety of protocols to achieve data transmission and receiving.


Python Socket working process: (Image from Network)


The socket is actually a module in Python that implements the ability to send and receive data.


Because the socket is a class, importing a module only requires using Socket.socket () to create a socket object.


    • Create a Socket format:

Sockets (Family=af_inet, Type=sock_stream, proto=0, Fileno=none)

Name of parameter Option name Role
Family Af_unix
Transferring data between processes in UNIX systems
Af_inet IPV4 Network Transmission data
Af_inet6 IPV6 Network Transmission data
Type Sock_stream
Streaming data, TCP

Sock_dgram Datagram-type data, UDP

Sock_raw
The original socket, the ordinary socket can not handle ICMP, IGMP and other network messages, and Sock_raw May, second, Sock_raw can also handle special IPV4 messages, in addition, using the original socket, you can use the IP_HDRINCL socket option by the user constructs the IP header.

Sock_rdm
is a reliable form of UDP that guarantees the delivery of datagrams but does not guarantee the order. Sock_ram is used to provide low-level access to the original protocol, which is used when certain special operations are required, such as sending ICMP packets. Sock_ram is typically used only by advanced users or by programs that are run by administrators.

Sock_seqpacket
Continuous packet transmission
Proto
0 The default is 0, which automatically selects the appropriate protocol based on the address cluster and the socket category
Fileno Default is None
If Fileno is specified, the other arguments be ignored, causing the socket with the specified file descriptor to return. Unlike SOCKET.FROMFD (), Fileno would return the same socket and not a duplicate. This could help close a detached socket using socket.close ().



    • Method of the Socket object:

      1, socket is divided into server and client.

      2, the TCP transmission does not need the IP,UDP transmission needs the IP address.

      3. The socket transfer string needs to be byte-type.

      4, list, dictionary and other data also need to change byte type. The JSON-processed function is byte-type and can be used in the send.


Method name Object Role
Bind (Address)
Service side Bind server-side address, IPv4, is the form of a tuple (address, port)
Listen (backlog) Service side Set number of client connections, number
Accept () Service side

Complete Reception information:

(<socket.socket fd=316, Family=addressfamily.af_inet, Type=socketkind.sock_stream, proto=0, laddr= (' 127.0.0.1 ', 6666), raddr= (' 127.0.0.1 ', 58775), (' 127.0.0.1 ', 58775))

<> part is socket information

The backend tuple is the guest address.

Connect (address) Client Bind server-side address, IPv4, is the form of a tuple (address, port)
CONNECT_EX () Client The function is the same as connect, but successfully returns 0, which fails to return the value of errno.
S.RECV (Bufsize[,flag]) Services and clients Accepts data for TCP sockets. The data is returned as a string, bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.
S.send (String[,flag]) Send TCP data. Sends data from a string to a connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string.
S.sendall (String[,flag])

Send TCP data in full. Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.

S.recvfrom (Bufsize[.flag]) Accepts data for UDP sockets. Similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data.
S.sendto (string[,flag],address) Send UDP data. Sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifying the remote address. The return value is the number of bytes sent.
S.close () Close the socket.
S.getpeername () Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).
S.getsockname () Returns the socket's own address. Typically a tuple (ipaddr,port)
S.setsockopt (Level,optname,value) Sets the value of the given socket option.
S.getsockopt (Level,optname[.buflen]) Returns the value of the socket option.
S.settimeout (Timeout) Sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as client connections waiting up to 5s)
Sk.fileno () File descriptor for sockets


    • Server-side Connection instance:

Import socketserver = socket.socket () server.bind ("localhost", 6666)    #  LocalHost is a local host and can also be written 172.0.0.1server.listen (6)                  #  allows 5 clients simultaneously while true:                      #  This position while is for the client to end, Wait for other clients to enter.     conn,addr = server.accept ()  #  receive a set of socket information, and address. Corresponds to the client's connect        while true:      &NBSP;&NBSP;&NBSP;CONN.RECV (1024x768)          #  server receive data first, You can change the value that is received each time, but not less than the values sent by the client.         conn.send (R ' 00000 ')                #  the character is preceded by R and becomes byte data before it can be transferred          #  hereis the main body of communication with each other, you can have multiple recv and send, it is necessary to note that a receive, and the client to the corresponding                          break                              #  end this client and continue listen other clients


    • Client Connection instance:

Import socketclient = Socket.socket () # Create socket Object Client.connect ((' localhost ', 6666) # Connection The hostname and port can also be the IP address of the string "127.0.0.1" while True:client.send (R ' 11111 ') client.recv (1024) # Here is the main body of communication, can have multiple recv and Sen D, it is important to note that the client should close the connection with the client to the corresponding breakclient.close () #.


    • The problem point of simple FTP making

Json.decoder.JSONDecodeError:Extra Data:

JSON cannot be decode because there is binary data in the process of transmission.


How do I return the transfer file when it is completed?

The client will receive a round. And in the transfer list, the first item is the flag, the second item is true, when the two items do not match, the prompt is incorrect, and the list of options is returned.



Sometimes the server runs a long time, not to receive statements, and the client sends the data too fast, resulting in an error

Add a sleep to the client ...



Logging use Filehandler Chinese garbled

When creating Filehandler, write the encode parameter

File_handler = logging. Filehandler (log_path,encoding= ' utf-8 ')


Call logging module, repeat output

1. Use RemoveHandler () to remove the handler from the logger.

2, in the log method to make a judgment, if this logger already have handler, then no longer add handler.


Dictionaries and lists cannot be transferred

Serialized with JSON after transfer. JSON serialized after the original is byte!




Python Basics: Network Programming Socket Basics

Related Article

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.