Python Network programming

Source: Internet
Author: User

Sockets are an abstract concept of network programming.

Usually we use a socket to indicate "open a network link", while opening a socket needs to know the destination computer's IP address and port number, and then specify the protocol type.

Socket classification

Sockets originated in the the 1970s UC Berkeley version of Unix, which is what people call BSD Unix. Therefore, sometimes people also refer to sockets as "Berkeley sockets" or "BSD sockets". Initially, sockets are designed to be used for communication between multiple applications on the same host. This is also called interprocess communication, or IPC. There are two types of sockets (or two races), which are file-based and network-based.

Socket family based on file type

Socket family name: Af_unix

Unix all files, file-based sockets are called by the underlying file system to fetch data, two sockets process running on the same machine, you can access the same file system to complete the communication indirectly

Socket family based on network type

Socket family name: af_inet

(There are also af_inet6 used for IPv6 and some other address families, but they are either used only on a platform, or have been discarded, or are rarely used, or are not implemented at all, and Af_inet is the most widely used one in all address families, Python supports a variety of address families, but since we only care about network programming, most of the time I use af_inet only)

Socket workflow

A scene in the life. You have to call a friend, dial first, a friend hears a phone call, and then you and your friend establish a connection, you can talk. When the communication is over, hang up the phone and end the conversation. the scene in life explains this work principle, perhaps the TCP/IP protocol family is born in the life, this is not necessarily.

Start with the server side. The server-side initializes the Socket, then binds to the port (BIND), listens to the port (listen), calls the accept block, waits for the client to connect. At this point if a client initializes a Socket and then connects to the server (connect), the client-server connection is established if the connection is successful. The client sends the data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction at the end.

Socket module Function Usage

The import socketsocket.socket (socket_family,socket_type,protocal=0) socket_family can be Af_unix or AF_INET. Socket_type can be sock_stream or sock_dgram. Protocol is generally not filled, the default value is 0. Gets the TCP/IP socket tcpsock = socket.socket (socket.af_inet, socket. SOCK_STREAM) Gets the UDP/IP socket udpsock = Socket.socket (socket.af_inet, socket. SOCK_DGRAM) Because there are too many properties in the socket module. We made an exception here by using the ' from module import * ' statement. With the ' from socket import * ', we take all the attributes in the socket module into our namespace, which can greatly reduce our code. For example Tcpsock = socket (af_inet, SOCK_STREAM)

  

Service end set of the function of solving words

S.bind () binds the address (host,port) to the socket and, under Af_inet, represents the address in the form of a tuple (host,port).

S.listen () starts TCP snooping. The backlog specifies the maximum number of connections that the operating system can suspend before rejecting the connection. This value is at least 1, and most applications are set to 5.

S.accept () passively accepts TCP client connections, (blocking) waits for a connection to arrive

Client sockets

S.connect () actively initializes the TCP server connection. The format of the general address is a tuple (hostname,port) and returns a socket.error error if there is an error in the connection

Extended version of the S.CONNECT_EX () connect () function, which returns an error code instead of throwing an exception when an error occurs

Public-use sockets

S.RECV () Receives TCP data, the data is returned as a string, and bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.
S.send () Sends the TCP data to the connected socket by sending the data in the string. The return value is the number of bytes to send, which may be less than the byte size of the string.
S.sendall () Complete sending of TCP data, complete sending of TCP data. 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.recvform () The UDP data is received, 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 () Sends UDP data, sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifies the remote address. The return value is the number of bytes sent.
S.close () Close 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 Connect ())
S.gettimeout () Returns the value of the current timeout, in seconds, or none if the timeout period is not set.
S.fileno () Returns the file descriptor for the socket.
S.setblocking (flag) If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to blocking mode (the default value). In nonblocking mode, if the call recv () does not find any data, or the Send () call cannot send the data immediately, the Socket.error exception is raised.
S.makefile () Create a file associated with the socket

Simple example

Server Side

Import Socketphone = Socket.socket (socket.af_inet,socket. SOCK_STREAM)  #创建基于tcp的网络 Socket Object Phone.bind (("127.0.0.1", 8000))   #把地址和端口号, bound to the Socket object print (">>>> >>>>>>>>> ") Phone.listen (5) #监听连接conn, addr = phone.accept ()   #被动接受TCP客户端连接msg = CONN.RECV (1024x768) #接收TCP数据, print ("The message sent by the client is >>", Msg.decode ("Utf-8")) user = input ("Send Message to client >>>") Conn.send (User.encode ("Utf-8")) #给client发送TCP数据, the transmission in the network must be in binary mode Conn.close () phone.close ()  #关闭套接字 # Note: This is a test made with your own native machine.

  

Client Side

Import Socketphone = Socket.socket (socket.af_inet,socket. SOCK_STREAM)  #创建socket对象  tcp mode Phone.connect (("127.0.0.1", 8000)) A = input (">>>") phone.send ( A.encode ("Utf-8")) data = PHONE.RECV (1024x768) print ("Message received from server", Data.decode ("Utf-8"))

  

Demonstration:

First run server side, waiting for client connection >>>>>>>>>>>>> the message sent by clients is >> hello please send message to client >>> received the second: connect the server to the appropriate IP address and port to send messages to the service >>>hello received the message received from the server

  

Python Network programming

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.