Python network programming, python network programming Basics

Source: Internet
Author: User

Python network programming, python network programming Basics
Understanding Socket

A socket is also called a "socket". It is used to describe the IP address and port. It is a communication chain handle. An application usually sends a request to or responds to a network request through "socket.

Socket originated from Unix, and one of the basic philosophies of Unix/Linux is "Everything is a file". For files, use the [open] [read/write] [close] mode to operate. Socket is an implementation of this mode. socket is a special file, and some socket functions are operations (read/write IO, open, and close) on it)

Difference between socket and file:

  • The file module is used to [open] [read/write] [close] a specified file]
  • The socket module is for the server and client Socket to [open] [read/write] [close]

Python (version 3.5) implements the simplest socket communication
 1 #!/usr/bin/env python 2 # coding=utf-8 3 # Author:Majh 4  5 import socket 6  7 ip_port = ('127.0.0.1', 9999) 8 sk = socket.socket() 9 10 sk.connect(ip_port)11 send_data = input('>>').strip()12 sk.send(bytes(send_data, encoding='utf-8'))13 recv_data = sk.recv(1024)14 print(str(recv_data, encoding='utf-8'))15 sk.close()
Client code
 1 #!/usr/bin/env python 2 # coding=utf-8 3 # Author:Majh 4  5 import socket 6  7 sk = socket.socket() 8 ip_port = ('127.0.0.1', 9999) 9 10 sk.bind(ip_port)11 print('sk.bind......')12 sk.listen(5)13 print('sk.listen......')14 conn, addr = sk.accept()15 print('conn:', conn)16 print('addr:', addr)17 18 read_data = conn.recv(1024)19 print('read_data', read_data)20 read_data = read_data.upper()21 22 conn.send(read_data)23 conn.close()
Server code

 

Socket keyword parameter:

 Sk = socket. socket (socket. AF_INET, socket. SOCK_STREAM, 0)

Parameter 1: address cluster

Socket. AF_INET IPv4 (default)
Socket. AF_INET6 IPv6

Socket. AF_UNIX can only be used for inter-process communication in a single Unix System

Parameter 2: Type

Socket. SOCK_STREAM streaming socket, for TCP (default)
Socket. SOCK_DGRAM datagram socket, for UDP

Socket. the original socket of SOCK_RAW. A common socket cannot process network packets such as ICMP and IGMP, while SOCK_RAW can. Secondly, SOCK_RAW can also process special IPv4 packets. In addition, the original socket, you can use the IP_HDRINCL socket option to construct an IP address header.
Socket. SOCK_RDM is a reliable UDP format, that is, ensure the delivery of datagram but not the order. SOCK_RAM is used to provide low-level access to the original protocol. It is used when special operations are required, such as sending ICMP packets. SOCK_RAM is generally only used by programs run by senior users or administrators.
Socket. SOCK_SEQPACKET reliable continuous packet Service

Parameter 3: Protocol

0 (default) is a protocol related to a specific address family. If it is 0, the system automatically selects a suitable protocol based on the address format and set type.

Sk. bind (address)

S. bind (address) binds the socket to the address. The address format depends on the address family. In AF_INET, the address is expressed in the form of a tuple (host, port.

Sk. listen (backlog)

Start listening for incoming connections. Backlog specifies the maximum number of connections that can be suspended before a connection is rejected.

Backlog = 5 indicates that the kernel has received a connection request, but the server has not called accept to process up to 5 connections.
This value cannot be infinitely large because the connection queue needs to be maintained in the kernel.

Sk. setblocking (bool)

Whether to block (True by default). If False is set, an error is returned if no data exists in accept and recv.

Sk. accept ()

Accept the connection and return (conn, address). conn is a new socket object and can be used to receive and send data. Address is the address used to connect to the client.

Receive TCP client connection (blocking) waiting for connection arrival

Sk. connect (address)

Connect to the socket at address. Generally, the format of address is tuples (hostname, port). If a connection error occurs, the socket. error is returned.

Sk. connect_ex (address)

The same as above, but there will be a return value. When the connection is successful, 0 is returned, and the encoding is returned when the connection fails, for example: 10061

Sk. close ()

Disable socket

Sk. recv (bufsize [, flag])

Accept socket data. Data is returned as a string, specified by bufsizeMaximumThe number of messages that can be received. Flag provides other information about messages, which can be ignored.

Sk. recvfrom (bufsize [. flag])

Similar to recv (), but the return value is (data, address ). Data is the string containing the received data, and address is the socket address for sending data.

Sk. send (string [, flag])

Send the data in the string to the connected socket. The returned value is the number of bytes to be sent, which may be smaller than the size of the string. That is, all specified content may not be sent.

Sk. sendall (string [, flag])

Send data in string to the connected socket, but try to send all data before returning. If None is returned successfully, an exception is thrown.

Internally, send all content by calling send recursively.

Sk. sendto (string [, flag], address)

Sends data to the socket. The address is a tuples in the form of (ipaddr, port) and specifies the remote address. The returned value is the number of bytes sent. This function is mainly used for UDP.

Sk. settimeout (timeout)

Sets the superperiod of socket operations. timeout is a floating point number in seconds. If the value is None, there is no superperiod. Generally, it should be set when the socket is just created during off-peak periods, because they may be used for connection operations (for example, a client connection can wait up to 5 s)

Sk. getpeername ()

Returns the remote address of the socket. The returned value is usually a tuples (ipaddr, port ).

Sk. getsockname ()

Return the address of the socket. It is usually a tuple (ipaddr, port)

Sk. fileno ()

Socket file descriptor

 

--------------------- To be continued -------------------------

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.