Python Road--python Basic 9--socket programming

Source: Internet
Author: User

first, Socket introduction

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 followed by tcp/ UDP standard.

Two, 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.

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 the 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 the end.

third, the use of socket module function

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

Iv. TCP-based sockets

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

#TCP Service SideSS= Socket ()#Create a server socketSs.bind ()#bind an address to a socketSs.listen ()#Monitoring LinksInf_loop:#Server Infinite loopcs = ss.accept ()#Accept Client LinksComm_loop:#Communication CycleCS.RECV ()/cs.send ()#dialog (receive and send)Cs.close ()#close the client socketSs.close ()#to turn off server sockets (optional)
# TCP Client  = socket ()     #  Create client Socket cs.connect ()      #  try to connect to server Comm_loop:        # Communication Cycle    Cs.send ()/cs.recv ()    #  Dialog (send/Receive)Cs.close ()                 #  close client sockets

chestnut:The socket communication process is similar to the call process, and we use the call example to implement a low version of socket communication:

#Service Side#_*_coding:utf-8_*___author__='YL'
Importsocket
Ip_port=('127.0.0.1', 9000)#Calling cardbufsize=1024#size of sending and receiving messages
S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)#buy a cell phoneS.bind (Ip_port)#Mobile Phone CardS.listen (5)#Phone Standbyconn,addr=s.accept ()#Phone Answering phone#PRINT (conn)#print (addr)Print('receive a call from%s'%addr[0]) msg=CONN.RECV (BUFSIZE)#listen to the news, obey.Print(Msg,type (msg)) Conn.send (Msg.upper ())#send a message, speakconn.close ()#Hang up the phones.close ()#Mobile phone off
#Client#_*_coding:utf-8_*___author__='YL'ImportSocketip_port=('127.0.0.1', 9000) BUFSIZE=1024s=Socket.socket (Socket.af_inet,socket. SOCK_STREAM) s.connect_ex (ip_port)#Dial PhoneS.send ('LHF NB'. Encode ('Utf-8'))#Send message, Talk (only byte type can be sent)Feedback=S.RECV (BUFSIZE)#receive the message, listen.Print(Feedback.decode ('Utf-8') ) S.close ()#Hang up the phone

Plus link loops and communication loops (continuous calls)

#Service SideImportSocketphone= Socket.socket (socket.af_inet, socket. SOCK_STREAM)#buy a cell phonePhone.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)#That 's it, in front of BIND plusPhone.bind (("127.0.0.1", 8080))#inserting a mobile cardPhone.listen (5)#Boot whileTrue:#Link Loopsconn, addr = Phone.accept ()#pick up the phone    Print("Client:", addr) whileTrue:#Communication Cycle        Try: Data= CONN.RECV (1024)#Receive Message            if  notData: Break             #client-side disconnection exception handling for Linux            Print("From client msg:%s"%data) Conn.send (Data.upper ())#Send Message        exceptException: Breakconn.close ()#Hang up the phonePhone.close ()#turn off the machine
#ClientImportsocketclient=Socket.socket (socket.af_inet, socket. Sock_stream) Client.connect (("127.0.0.1", 8080))#Dial Phone whiletrue:msg= Input (">>>:") Client.send (Msg.encode ("Utf-8")) Data= CLIENT.RECV (1024)    Print(data) client.close ()

v. UDP-based sockets

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

# UDP service Side  = socket ()   # Create a server socket ss.bind ()       # bind server socket Inf_loop:       # server infinite loop    # dialog (receive and send)ss.close ()                         #  Close server sockets

# UDP Client  = socket ()   #  Create client socket Comm_loop:      #  communication Loop    cs.sendto ()/ Cs.recvfrom ()   #  Dialog (send/Receive)Cs.close ()                      #  close client sockets

Chestnuts: A Simple example of UDP sockets

# _*_coding:utf-8_*_ Import socketip_port= ('127.0.0.1', 9000) BUFSIZE=1024udp_server_client =Socket.socket (socket.af_inet,socket. SOCK_DGRAM) Udp_server_client.bind (ip_port) while True:    msg,addr=udp_server_ Client.recvfrom (BUFSIZE)    print(msg,addr)    udp_server_client.sendto (Msg.upper (), Addr)

Python Road--python Basic 9--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.