Python Learning: 20.Python network Programming (Socket)

Source: Internet
Author: User

First, Socket introduction

We know that two processes if communication is required, the most basic prerequisite is the ability to uniquely identify a process. In the local process communication can use PID to uniquely identify a process, but the PID is only local only, the network of two process PID collision probability is very large, this time need to separate its path. The TCP/IP protocol family solves this problem. The IP address of the network layer IP layer can uniquely identify the host in the network, and the "protocol + port number" of the TCP layer of the transport layer can uniquely identify a process of the host, so that the ternary "IP address + protocol + port number" can uniquely indicate a process in the network, Process communication in the network can use this flag to communicate with other processes.
What is a socket? The socket is often translated into sockets, which is an abstraction layer between the application layer and the transport layer, which abstracts the complex operations of the TCP/IP layer into a few simple interfaces to provide layer calls to implement the process of communication in the network.
Socket originated from UNIX, in Unix everything is file philosophy, socket is an "open-read/write-off" mode implementation, the server and the client maintain a "file", after the establishment of the connection opened, you can write to the file for the other side to read or read the contents of the other side, Closes the file at the end of the communication.

Second, the socket communication process

Example of a socket that uses TCP protocol communication

Third, the socket Code implementation

We need a server, then one or more clients to connect

Python supports three ways of connecting, one TCP is UDP, and the other is a connection between processes and processes that are uniquely supported in Python.

Service side

Run up (specify IP and port), wait for someone else to connect, here the default parameter is to use a TCP connection.

Simple code implementation, just a connection

ImportSocket#creating a Socket objectSK =socket.socket () Sk.bind ('127.0.0.1', 9999,)) Sk.listen (5)#the number of listeners can be 5 . whileTrue:#receiving requests from clients    #connection, address information for the clientConn,address = Sk.accept ()#here will block until someone comes to connect    Print(conn,address) output results:<socket.socket fd=276, Family=addressfamily.af_inet, Type=socketkind.sock_stream, proto=0, Laddr= ('127.0.0.1', 9999), Raddr= ('127.0.0.1', 53185) > ('127.0.0.1', 53185)

Client

Connecting to the service side

Import= socket.socket ()# connects to server obj.connect ('127.0.0.1  ', 9999,)) Obj.close ()

Four, socket parameter function analysis

SK = Socket.socket (socket.af_inet,socket. sock_stream,0)

Parameter one: Address cluster

Socket.af_inet IPv4 (default)
Socket.af_inet6 IPV6

Socket.af_unix can only be used for single UNIX system interprocess communication

Parameter two: type

Socket. Sock_stream streaming socket, for TCP (default)
Socket. SOCK_DGRAM datagram socket, for 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 particular address family, if 0, the system will automatically select an appropriate protocol based on the address format and socket category.

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 the accept to process the maximum number of connections is 5
This value cannot be infinitely large 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. That is, the specified content may not be sent all.

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.

Internally, the send is called recursively, sending all the content.

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

V. Realization of server and client information communication

Service side

ImportSocket#creating a Socket objectSK =socket.socket () Sk.bind ('127.0.0.1', 9999,)) Sk.listen (5)#the number of listeners can be 5 . whileTrue:#receiving requests from clients    #connection, address information for the clientConn,address = Sk.accept ()#here will block until someone comes to connect    #When someone comes to connect, send the following message to the clientConn.sendall (Bytes ('Welcome to visit', encoding='Utf-8'))#send in byte format     whiletrue:ret_bytes= CONN.RECV (1024) Ret_str= STR (ret_bytes,encoding='Utf-8')        ifRet_str = ='Q':             Break        Else: Conn.sendall (bytes (ret_str+'yes, okay.', encoding='Utf-8'))            Print(address)

Client

ImportSocketobj=Socket.socket ()#Connect to ServerObj.connect (('127.0.0.1', 9999,)) STRs= OBJ.RECV (1024)#Receive server-side information, 1024 indicates the most to receive 1024 bytes, more than 1024 can not be received at a time to complete#The recv here is also blocked, after receiving information from the server, will continue to execute the following codePrint(Str (strs,encoding='Utf-8')) whileTRUE:INP= Input ('Please enter what you want to send')    ifINP = ='Q': Obj.sendall (bytes (inp,encoding='Utf-8'))         Break    Else: Obj.sendall (bytes (inp,encoding='Utf-8')) RET= str (OBJ.RECV (1024x768), encoding='Utf-8')        Print(ret)

Python Learning: 20.Python network Programming (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.