[Python] probing socket

Source: Internet
Author: User

1. What is a socket?

Socket Chinese translation: socket, but we generally agree to commonly known as the use of: socket. I want to explain what the socket is for before explaining what it is for: the socket is to establish the basis of ' communication ', establish the connection, transmit the data ———— ' communication endpoint '.

My understanding: Each socket object is an abstract ' communication object ', and the ' communication object ' does something that sends or receives information. Just want to live: Each networked computer is a socket object, and each person who calls is also a socket object.

Every programming language is almost ready for the socket class, why? Have you ever seen a computer that can't surf the internet? With the socket class, we just need to invoke this class to happily do the network programming, which is what we'll say next: Socket programming in Python.

Socket programming in 2.python

As stated above, the socket is the transmission of data, how is transmission data transmitted? To be efficient or to be accurate? So the socket is divided into two types: connection-oriented and no-connection.

    1. Connection-oriented: The TCP protocol used is to establish a reliable connection before the data is transmitted, and then the data is transmitted in the form of a byte stream. So that the data is reliable, non-repeatable, and orderly. Because it is a byte stream, there is no data boundary, it can split a piece of data into multiple parts, which facilitates the efficiency of transmission.

    2. No connection: Use of the UDP protocol, the transmission of data before the need to establish a connection, data transmission in the form of a message.

Summary : The difference between the two is whether to establish a connection; the form of data transfer (message or data stream)

TCP sockets

TCP Socket Communication Flowchart:

Here's an example of using the Python language to write server-side:

# Coding:utf-8# Server-side codeImport socketPrint' I am the service side! ' HOST=' PORT=50007 s= Socket.socket (socket.af_inet, socket. SOCK_STREAM)# Create TCP Socket Object S.bind ((HOST, PORT))# Bind Address S.listen (1)# Monitor tcp,1 representative: Allow up to 1 connections at a time conn, addr= s.accept () # started passively accepting connections from TCP clients. print  ' connected address ', repr (addr) while 1:data = conn.recv (1024) # accept TCP data, 1024 indicates the size of the buffer if not data: break print  ' Received: ', repr (data) conn.sendall (data) # send the data received from the client intact, sent to the client conn.close ()       

Now the server side of the TCP socket has started listening: 50007 port, waiting for the client connection. The next step is to write the client socket, which allows the two soket to connect and generate communication.

# Coding:utf-8Import socketPrint' I am the client! ' HOST= "localhost" # server Ipport = 50007 # the port of the server to be connected s = socket.socket (socket.af_inet, Socket.) SOCK_STREAM) S.connect ((HOST, PORT) print  "send ' Hello World '" S.sendall ( ' Hello, World ') # send ' Hello,world ' to server data = s.recv ( 1024x768) S.close () print  "received ', repr (data) # print data received from the server     

Let them run up:

    1. python server.py, run the server-side code First
    2. To open another terminal, python client.py run the code for the client
    3. The results are as follows:
UDP Socket

UDP is no connection, while sending a message, so there are some different from the TCP socket, refer to the following socket method and property sheet, modify the above code on it.

1.Socket type

Socket format:
Socket (family, type[,protocal]) creates a socket with the given address family, socket type, protocol number (default = 0).

Address family

Address Family Description
Socket.af_unix Can only be used for single UNIX system interprocess communication (local communication)
Socket.af_inet network communication between servers
Socket.af_inet6 Use the IPV6 address to communicate

Socket type

Socket Type Description
Socket. Sock_stream Streaming socket, for TCP
Socket. Sock_dgram Datagram socket for UDP


Example Description
Create a TCP Socket S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Create a UDP Socket S=socket.socket (Socket.af_inet,socket. SOCK_DGRAM)
2.Socket function
    1. When TCP sends data, a TCP connection is established, so you do not need to specify an address. UDP is for non-connected, each time it is sent to specify who to send.
    2. The server and client cannot send lists, tuples, dictionaries directly. Only String (repr (data) or str (data) can be passed.

Service-Side socket function

service-side socket function Description
S.bind (Address) Binds a socket to an address, and under Af_inet, the address is represented as a tuple (host,port).
S.listen (Backlog) Starts listening for TCP incoming connections. 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 () Accepts a TCP connection and returns (Conn,address), where Conn is a new socket object that can be used to receive and send data. Address is the location of the connection client.

Client socket function

Client socket function Description
S.connect (Address) The socket that is connected to the address. 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.
S.CONNECT_EX (adddress) function is the same as connect (address), but successfully returns 0, the value of errno is returned.

Common socket function

Common socket function Description
S.RECV (Bufsize[,flag]) 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 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

Sticky, subcontracting, non-blocking sockets for full duplex?

[Python] probing socket

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.