Basic Python Learning (eight)

Source: Internet
Author: User

Python3 socket

Python provides two levels of access to network services. :

    • The low-level network service supports the basic socket, which provides the standard BSD Sockets API to access all the methods of the underlying operating system socket interface.
    • High-level Network Service Module Socketserver, which provides a server-centric class that simplifies the development of Web servers

Scoket () function

The syntax format is as follows:

Socket.socket ([Soc[type[proto]])
Parameters
    • SOC: Socket family can make Af_unix or af_inet
    • Type: The socket type can be divided into either a connection-oriented or a non-connected SOCK_STREAMSOCK_DGRAM
    • Protocol: General does not fill the default is 0
Socket object (built-in) method
function Description
Server-side sockets
S.bind () The binding address (Host,port) to the socket, under Af_inet, represents the address in the form of a tuple (host,port).
S.listen () Start 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 initializing 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.
S.CONNECT_EX () Extended version of the Connect () function, which returns an error code instead of throwing an exception when an error occurs
Socket functions for public use
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

A simple instance server
#!/usr/bin/env python#-*-coding:utf-8-*-#Author:jerry ShiImportSocket,sys#creating a Socket objectServerSocket =Socket.socket (socket.af_inet, socket. SOCK_STREAM)#get Local Host nameHost =socket.gethostname () port= 9999#Binding PortServersocket.bind ((host, port))#set maximum number of connections, queue afterServersocket.listen (5) whileTrue:#Establish client ConnectionsClientsocket, addr =serversocket.accept ()Print("Connection address:%s"%str (addr)) msg='Welcome to the test program! '+"\ r \ n"clientsocket.send (Msg.encode ('Utf-8')) Clientsocket.close ()

##### #结果 ######
Connection address: (' 192.168.1.2 ', 55053)
Client
#!/usr/bin/env python#-*-coding:utf-8-*-#Author:jerry ShiImportSocket,sys#creating a Socket objects =Socket.socket (socket.af_inet, socket. SOCK_STREAM)#get Local Host nameHost =Socket.gethostname ()#Set Port GoodPort = 9999#connection service, specifying host and PortS.connect ((host, port))#receive less than 1024 bytes of datamsg = S.RECV (1024) S.close ()Print(Msg.decode ('Utf-8'))

##### #结果 #####
Welcome to the test program!

Python Basic Learning (eight)

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.