Python's socket detailed

Source: Internet
Author: User

Socket programming 1. Basic concepts
1.什么是客户端/服务器架构?服务器就是一系列硬件或软件,为一个或多个客户端(服务的用户)提供所需的“服务”。它存在唯一目的就是等待客户端的请求,并响应它们(提供服务),然后等待更多请求。说白了就是一个提供服务,一个请求服务得到相应的一个过程。2.套接字:通信端点套接字是计算机网络数据结构,它体现了上节中描述的“通信端点”的概念。在任何类型的通信开始之前,网络应用程序必须创建套接字。可以将它们比作电话插孔,没有它将无法进行通信。Python只支持AF_UNIX、AF_NETLINK、AF_TIPC 和 AF_INET ,重点使用基于网络的AF_INET.3.套接字地址:主机-端口对它是网络通信过程中端点的抽象表示,python使用元组保存:ADDR = (HOST,PORT)。4.套接字类型流式套接字(SOCK_STREAM):用于提供面向连接、可靠的数据传输服务。数据报套接字(SOCK_DGRAM):提供了一种无连接的服务。该服务并不能保证数据传输的可靠性,数据有可能在传输过程中丢失或出现数据重复,且无法保证顺序地接收到数据。
2.Python Network Programming 2.1 Common socket object methods and properties
name Description
Service side Server Socket method
S.bind (ADDR) Bind an address (host name, port number pair) to a socket
S.listen ([backlog]) Set up and start the TCP listener, if the backlog is specified, must be at least 0 (if less than 0, set to 0);
S.accept () Passively Accept TCP client connections and wait until the connection arrives (blocked)
Client Client Socket method
S.connect () Proactively initiate TCP server connections
S.CONNECT_EX () Extended version of Connect (), which returns the problem as an error code instead of throwing an exception
General General Common socket methods
S.RECV () Receiving TCP messages
S.recv_into () Receives a TCP message to the specified buffer
S.send () Sending a TCP message
S.sendall () Send a TCP message in full
S.recvfrom () Receiving UDP messages
S.recvfrom_into () Receives a UDP message to the specified buffer
S.sendto () Send UDP message
S.getpeername () Connect to the remote address of the socket (TCP)
S.getsockname () Address of the current socket
S.getsockopt () Returns the value of the given socket option
S.setsockopt () Sets the value of a given socket option
S.shutdown () Close connection
S.close () Close socket
S.detach () Closes the socket without closing the file descriptor, returns the file descriptor
S.ioctl () Mode to control sockets (Windows only)
Blocking Blocking-oriented socket method
S.setblocking () To set blocking or non-blocking mode for sockets
S.settimeout () To set the timeout period for blocking socket operations
S.gettimeout () Gets the timeout period for blocking socket operations
File method File-oriented socket methods
S.fileno () File descriptor for sockets
S.makefile () To create a file object associated with a socket
Property Data properties
S.family Socket family
S.type Socket type
S.proto Socket protocol
2.2 Creating a service and client 2.2.1 Creating a TCP Service

The general creation process:

ss = socket()       #  创建服务器套接字ss.bind(ADDR)       #  套接字与地址绑定ss.listen()         #  监听连接while True:         #  服务器无限循环cs = ss.accept()    #  接受客户端连接comm_loop:          #  通信循环cs.recv()/cs.send() #  对话(接收 / 发送)cs.close()          #  关闭客户端套接字ss.close()          #  关闭服务器套接字 # (可选)
2.2.2 Creating a TCP Client

The general creation process:

cs = socket()       #  创建客户端套接字cs.connect()        #  尝试连接服务器comm_loop:          #  通信循环cs.send()/cs.recv() #  对话(发送 / 接收)cs.close()          #  关闭客户端套接字
2.2.3 Creating a UDP service

The general creation process:

ss = socket()       #  创建服务器套接字ss.bind(ADDR)       #  套接字与地址绑定while True:         #  服务器无限循环ss.sendto()         #  发送 ss.recvfrom()       #  接收ss.close()          #  关闭服务器套接字 # (可选)
2.2.4 Creating a UDP Client

The general creation process:

cs = socket()       #  创建客户端套接字comm_loop:          #  通信循环cs.sendto()         #  发送 cs.recvfrom()       #  接收cs.close()          #  关闭客户端套接字

server.py Code

Import socketfrom time Import ctimeimport jsonimport timehost = ' Port = 9001ADDR = (HOST, port) buffsize = 1024max_listen = 5def TCPServer (): # TCP Service # with Socket.socket () as S:with socket.socket (socket.af_inet, socket. SOCK_STREAM) as S: # BIND server address and Port S.bind (ADDR) # Boot Service listener s.listen (max_listen) print (' Wait for user to connect Into............ ') while True: # waits for a client connection request, gets Connsock conn, addr = S.accept () print (' Warning, remote client: {} access System!!! '. Format (addr)) with Conn:while True:print (' Receive request information .....                    ') # receive request Information data = CONN.RECV (buffsize) print (' data=%s '% data) Print (' receive data: {!r} '. Format (Data.decode (' Utf-8 ')) # sends the request data Conn.send ( Data.encode (' Utf-8 ')) print (' Send return complete!!! ') S.close () # Create UDP service def udpserver (): # Create UPD server end sockets with Socket.socket (Socket.af_inet, SOcket. SOCK_DGRAM) as S: # bind address and Port S.bind (ADDR) # wait to receive information while True:print (' UDP service started, ready to receive data 。。。            ') # to receive data and client request addresses, address = S.recvfrom (buffsize) if not data:break Print (' Receive request information: {} '. Format (Data.decode (' Utf-8 ')) s.sendto (b ' I am udp,i got it ', address) S.clo SE () if __name__ = = ' __main__ ': while true:choice = input (' Input choice t-tcp or u-udp: ') if choice! = ' t            ' and choice! = ' U ': print (' please input t or U,ok? ') Continue if choice = = ' t ': print (' Execute tcpsever ') tcpserver () Else:prin T (' Execute udpsever ') udpserver ()

client.py code

Import socketfrom time Import ctimehost = ' localhost ' PORT = 9001ADDR = (HOST, PORT) ENCODING = ' utf-8 ' buffsize = 1024def TC Pclient (): # Creates a client socket with Socket.socket (Family=socket.af_inet, Type=socket. SOCK_STREAM) as S: # try to connect server S.connect (ADDR) print (' Connection service succeeded!!                ') # communication loop While True:indata = input (' pleace input something: ') if inData = = ' Q ': Break # Send data to server InData = ' [{}]:{} '. Format (CTime (), InData) S.send (Indata.enco De (ENCODING)) print (' Send successfully! ') # receive return Data Outdata = S.RECV (buffsize) print (' Return data information: {!r} '. Format (outdata)) # Close Customer End Socket S.close () def udpclient (): # Creates a client socket with Socket.socket (socket.af_inet, socket. SOCK_DGRAM) as S:while True: # Send message to server data = input (' "Please input message to server or Inpu T \ ' quit\ ': ') if data = = ' quit ': Break data = ' [{}]:{} '. fOrmat (CTime (), data) s.sendto (Data.encode (' Utf-8 '), ADDR) print (' Send Success ') # Receive server return Information RecvData, Addrs = S.recvfrom (buffsize) print (' recv message: {} '. Format (Recvdata.decode (' Utf-8 ')) # Close Socket S.close () if __name__ = = ' __main__ ': while true:choice = input (' Input choice t-tcp or U- UDP or Q-quit: ') if choice = = ' Q ': break if choice! = ' t ' and choice! = ' U ': print (' pl            Ease input t or U,ok? ') Continue if choice = = ' t ': print (' Execute tcpsever ') tcpClient () Else:prin T (' Execute udpsever ') udpclient ()

Code Description : The first execution, python server.py in the execution python client.py , you can test tpc/udp simple communication.

Python's socket detailed

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.