The--socket of Python learning

Source: Internet
Author: User

1.Socket Overview

The two programs on the network realize the exchange of data through a two-way communication connection, one end of this connection is called a socket. Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and are a handle to a chain of communication, where applications usually make requests to the network through "sockets" or respond to network requests.

Sockets originate from UNIX, and one of the basic philosophies of unix/linux is "Everything is file", and the file is operated with "open" "Read and Write" "Off" mode. Socket is an implementation of this pattern, the socket is a special kind of file, some of the socket function is to do it (read/write Io, open, close).

Plain English explained: Two programs use the socket through "network" interaction data, it is only responsible for two things: Establish a connection, pass the data.

The difference between a socket and a file:

    1. The file module is "open", "Read and write" "Close" for a specified document
    2. The socket module is "open", "Read and write" "Off" for server-side and client sockets

Use a professional chart to interpret:

Let's look at an example to show how the socket is implemented:

Server-side code:

ImportSocketobj_server= Socket.socket ()#Create an instance equivalent to Socket.socket (socket.af_inet,socket. sock_stream,0)Obj_server.bind (('localhost', 1234))#the ability to accept tuplesObj_server.listen (5)#up to 5 connections accepted whileTrue:Print "waiting ....."        #The program starts when printing waiting ...CONN,ADDR = Obj_server.accept ()#waiting to be acceptedClinet_date = CONN.RECV (1024)#accepts up to 1024 bytes    PrintClinet_date#Print out the code that came from the client sideConn.send ('message') Conn.close ()

Clinet-Side code:

Import= socket.socket () obj.connect('localhost', 1234)           # note the port number to be consistent with server side obj.send ('SOS')              # send SOS to server side Server_data = obj.recv (1024x768)print server_data            # Print out the information sent from the server side Obj.close ()

Let's look at the results of the execution:

Clinet End:

Server side:

The server side received the message sent from the client side ' SOS '. and sent a confirmation message to the client that we received this message on the client side. This is the process of data interaction. Send is a message method, and Recv is the method of receiving messages. We only need to modify the contents of send and recv to realize the data interaction between the two programs.

Socket implementation is like a courier to take the process of delivery, the parcel is the server side, Courier is the client side, send and recv content is what we want to send something, then ready to send something, we have to tell the courier where to pick up the pieces, Look at the Sock.bind method in the server, which passed a tuple (' IP ', ' Port ') to bind method, is to put the parcel at this address of the port waiting for the courier, and the client side of the Obj_ Client.connect method is to tell The courier, go to that address to find the port to pick up the parcel. So the IP and port content in this tuple must be the same, I and the courier about good. I send the content does not matter what, I send what, the client recv what, because I want to send what, the courier to get is what, he has no right to what I send something.

2. Parameter interpretation

for a UDP socket.  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, the use of the original socket, can be IP_  The HDRINCL socket option constructs an IP header by the user. Socket. 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. Socket. Sock_seqpacket reliable Continuous Packet service parameter three: protocol 0 (default) protocol related to a specific address family, if 0, the system will automatically select an appropriate protocol based on the address format and socket category .

UDP can implement sockets, the answer is obvious, the following is an example.

Server code:

Import= ('127.0.0.1', 9999= Socket.socket (socket.af_inet, Socket. sock_dgram,0) while True:    = raw_input (' data:'). Strip ()     if'exit':        break     sk.sendto (Inp,ip_port) sk.close ()

Clinet-Side code:

Import= ('127.0.0.1', 9999= Socket.socket (socket.af_inet, Socket. sock_dgram,0) Sk.bind (ip_port) while True:    = sk.recv (1024x768)    Print data

The results of the implementation are as follows:

Sk.bind (Address)

S.bind binds the socket to the address. The format of address addresses depends on the address family. Under Af_inet, address is represented as a tuple (host,port).
Sk.listen (backlog)
Start listening for incoming connections. The backlog specifies the maximum number of connections that can be suspended before a connection is rejected. The backlog equals 5, indicating that the kernel has received a connection request, but the server has not yet called accept to handle the maximum number of connections 5 This value cannot be infinite because the connection queue is maintained in the kernel

Sk.setblocking (BOOL)

Whether blocking (default true), if set to false, then the accept and recv when there is no data, the error.
sk.accept ()
Accepts the 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. Incoming TCP Client connection (blocked) waiting for connection

Sk.connect (Address)

The socket that is connected to the address. Generally, address is in the form of a tuple (Hostname,port) and returns a socket.error error if there is an error in the connection.

SK.CONNECT_EX (Address)

Ditto, but there will be a return value, the connection succeeds when the return 0, the connection fails when the return encoding, for example: 10061

Sk.close ()

Close socket

SK.RECV (Bufsize[,flag])

Accepts the data for the socket. The data is returned as a string, and bufsize specifies the maximum quantity that can be received. Flag provides additional information about the message, which can usually be ignored.

Sk.recvfrom (Bufsize[.flag])

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.

Sk.send (String[,flag])

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.

Sk.sendall (String[,flag])

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

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

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. This function is mainly used for UDP protocol.

Sk.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.getpeername ()

Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).
Sk.getsockname ()
Returns the socket's own address. Typically a tuple (ipaddr,port)

Sk.fileno ()

File descriptor for sockets

The--socket of Python learning

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.