Python's socket programming

Source: Internet
Author: User

First, what is the socket

  A socket is an intermediate software abstraction layer that the application layer communicates with the TCP/IP protocol family, which is a set of interfaces. In design mode, thesocket is actually a façade mode, it is the complex TCP/IP protocol family hidden behind the socket interface, for the user, a set of simple interface is all, let the socket to organize data to meet the specified protocol.

So, we do not need to understand the TCP/UDP protocol, the socket has been packaged for us, we only need to follow the socket rules to program, write the program is naturally follow the TCP/UDP standard.

Some people also say that the socket is used to identify the location of a host in the Internet, and port is used to identify an application on this machine, the IP address is configured on the network card, and the port is the application Ip+port,ip, The IP-Port binding identifies an application that is unique to the Internet, and the PID of the program is the identity of the different processes or threads on the same machine.
II. history and classification of sockets

1 . Socket family based on file type

    Socket family name: Af_unix

Unix all files, file-based sockets are called by the underlying file system to fetch data, two sockets process running on the same machine, you can access the same file system to complete the communication indirectly

2 . Socket family based on network type

    Socket family name: af_inet

(There are also af_inet6 used for IPv6 and some other address families, but they are either used only on a platform, or have been discarded, or are rarely used, or are not implemented at all, and Af_inet is the most widely used one in all address families, Python supports a variety of address families, but since we only care about network programming, most of the time I use af_inet only)

three, socket work flow

A scene in the life. You have to call a friend, dial first, a friend hears a phone call, and then you and your friend establish a connection, you can talk. When the communication is over, hang up the phone and end the conversation. The scene in life explains how this works.

Figure 3

Start with the server side. The server-side initializes the Socket, then binds to the port (BIND), listens to the port (listen), calls the accept block, waits for the client to connect. At this point if a client initializes a Socket and then connects to the server (connect), the client-server connection is established if the connection is successful. The client sends a data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction at once .

Socket () module function usage

The import socketsocket.socket (socket_family,socket_type,protocal=0) socket_family can be Af_unix or AF_INET. Socket_type can be sock_stream or sock_dgram. Protocol is generally not filled, the default value is 0. Gets the TCP/IP socket tcpsock = socket.socket (socket.af_inet, socket. SOCK_STREAM) Gets the UDP/IP socket udpsock = Socket.socket (socket.af_inet, socket. SOCK_DGRAM) Because there are too many properties in the socket module. We made an exception here by using the ' from module import * ' statement. With the ' from socket import * ', we take all the attributes in the socket module into our namespace, which can greatly reduce our code. For example Tcpsock = socket (af_inet, SOCK_STREAM)

  

service-side socket functions
S.bind () binding (host, port number) to socket
S.listen () Start TCP listener
S.accept () passively accepts a TCP client connection, (blocking) waits for a connection to arrive

Client Socket Functions
S.connect () Active initialization of TCP server connections
Extended version of the S.CONNECT_EX () connect () function, which returns an error code instead of throwing an exception when an error occurs

socket functions for public use
S.RECV () Receiving TCP data
S.send () sends TCP data (send data is lost when the amount of data to be sent is greater than the remaining space in the cache)
S.sendall () sends the full TCP data (essentially a cyclic call Send,sendall the data is not lost when the amount of data to be sent is greater than the remaining space in the buffer, and the call to send is sent until it is finished)
S.recvfrom () receiving UDP data
S.sendto () Send UDP data
S.getpeername () The address of the remote that is connected to the current socket
S.getsockname () address of the current socket
S.getsockopt () returns the parameters of the specified socket
S.setsockopt () Sets the parameters of the specified socket
S.close () Close socket

lock-oriented socket method
S.setblocking () sets the blocking and non-blocking mode for sockets
S.settimeout () Sets the timeout period for blocking socket operations
S.gettimeout () Gets the timeout period for blocking socket operations

functions for file-oriented sockets
S.fileno () The file descriptor of the socket
S.makefile () Create a file associated with the socket

1: Quick description of socket communication using the call Process 2: Server and client plus one-link-based circular communication 3: The client sends an empty, card master, which proves to be from which location the card's service side: from socket import *phone=socket (af_inet, Sock_stream) Phone.bind ((' 127.0.0.1 ', 8081)) Phone.listen (5) conn,addr=phone.accept () while TRUE:DATA=CONN.RECV (1024 ) Print (' server===> ') print (data) conn.send (Data.upper ()) Conn.close () Phone.close () client: from socket import *phon    E=socket (Af_inet,sock_stream) phone.connect ((' 127.0.0.1 ', 8081)) while True:msg=input (' >>: '). Strip () Phone.send (Msg.encode (' Utf-8 ') print (' client====> ') data=phone.recv (1024x768) print (data) Description Card reason: The buffer is empty recv is stuck, the principle of extraction Figure 4. Demo client disconnects, service side case, provides workaround 5. The demo server cannot repeat the link, and the servers are running continuously to accept customer Links 6: Simple demo UDP server from socket import *phone=socket (af_ Inet,sock_dgram) Phone.bind ((' 127.0.0.1 ', 8082)) while True:msg,addr=phone.recvfrom (1024x768) phone.sendto (Msg.upper (), Addr) client from socket to import *phone=socket (Af_inet,sock_dgram) while True:msg=input (' >>: ') phone.sendto (Msg.enc   Ode (' Utf-8 '), (' 127.0.0.1 ', 8082)) Msg,addr=phone.recvfrom (1024) The print (MSG) UDP client can concurrently demonstrate that the UDP client can enter as an empty demo, say the difference between recvfrom and recv, and leave out the concept of TCP stream and UDP, leaving it to the sticky bag to say readers do not read: Socket experiment deduction process 
Iv. TCP-based sockets

TCP is link-based, you must start the server, and then start the client to link the server

TCP Service Side  

SS = socket () #创建服务器套接字ss. bind ()      #把地址绑定到套接字ss. Listen ()      #监听链接inf_loop:      #服务器无限循环    cs = ss.accept () # Accept Client link    comm_loop:         #通讯循环        cs.recv ()/cs.send () #对话 (Receive and send)    cs.close ()    #关闭客户端套接字ss. Close ()        #关闭服务器套接字 (optional)

TCP Client

CS = socket ()    # Create client Socket Cs.connect ()    # Try to connect to server Comm_loop:        # Communication Loop     Cs.send ()/cs.recv ()    # Dialog (Send/ Receive) Cs.close ()            # Close Client sockets

The socket communication process is similar to the call process, so we use the phone as an example to implement a low version of socket communication

#_ *_coding:utf-8_*_
__author__ = ' Linhaifeng '
Import socket
ip_port= (' 127.0.0.1 ', 9000) #电话卡
bufsize=1024 #收发消息的尺寸
S=socket.socket (Socket.af_inet,socket. SOCK_STREAM) #买手机
S.bind (Ip_port) #手机插卡
S.listen (5) #手机待机


Conn,addr=s.accept () #手机接电话
# PRINT (conn)
# Print (addr)
Print (' Received phone from%s '%addr[0])

MSG=CONN.RECV (BUFSIZE) #听消息, obedient
Print (Msg,type (msg))

Conn.send (Msg.upper ()) #发消息, Speak

Conn.close () #挂电话

S.close () #手机关机

Service side

#_ *_coding:utf-8_*___author__ = ' Linhaifeng ' Import socketip_port= (' 127.0.0.1 ', 9000) Bufsize=1024s=socket.socket ( Socket.af_inet,socket. SOCK_STREAM) s.connect_ex (ip_port)           #拨电话s. Send (' Linhaifeng nb '. Encode (' Utf-8 '))         #发消息, Speak (send byte type only) feedback =S.RECV (BUFSIZE)                           #收消息, obedient print (Feedback.decode (' Utf-8 ')) s.close ()                                       #挂电话客户端

Eight UDP-based sockets

UDP is non-linked, starting at which end will not error

Python's socket programming

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.