Python3 Socket Network Programming

Source: Internet
Author: User

A socket is also called a socket, and an application usually makes a request to the network through a "socket" or responds to a network request, making it possible to communicate between hosts or between processes on a computer.

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 establishing a connection open, you can write to their own files for the other side to read or read the contents of the other side, Closes the file at the end of the communication. The English meaning of the socket is "slot" or "socket", just like our home landline, if there is no network cable of that socket, the phone is unable to communicate. The socket is an interface for implementing the TCP,UDP protocol and facilitates the use of TCP,UDP.

# Process Description: # # 1 server created based on address type (IPV4,IPV6), socket type, protocol create socket# # 2 server for socket bound IP address and port number # # 3 server Socket Listener port number request, ready to receive client-sent connections, This time the server socket is not opened # # 4 client created socket# # 5 client open socket, based on server IP address and port number trying to connect server socket# # 6 server socket received client socket request, passive open, Begins receiving client requests until the client returns connection information. At this time the socket enters the blocking state, # The   so-called blocking is the Accept () method until the client returns the connection information, and begins receiving the next client connection request # # 7 Client connection succeeded, send connection status information to the server # # 8 The server Accept method returns, Connection succeeded # # 9 The client writes information to the socket (or writes information to the socket by the Service) # # 10 Server Read information (client read information) # # 11 Client off # # 12 server-side off

Socket object (built-in) method
The server-side s.bind () # Bind address (Host,port) to the socket, under Af_inet, represents the address in the form of a tuple (host,port). S.listen () # starts 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 at the client S.connect () # to actively initialize a 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. Extended version of the S.CONNECT_EX () # Connect () function, which returns an error code when an error occurs, instead of throwing an exception to the public-use function s.recv () # Receives TCP data, the data is returned as a string, bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored. S.send () # sends TCP data to send 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. S.sendall () # Sends TCP data intact, sending TCP data completely. 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.close () # Close Socket S.recvform () # receives UDP data, 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), and specifies the remote address. The return value is the number of bytes sent. 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, because they may be used for connected operations (such as Connect ()) s.gettimeout () # Returns the value of the current timeout period, in seconds, or none if no timeout has been set. S.fileno () # Returns the file descriptor of the socket. S.setblocking (flag) # If flag is 0, set the socket to nonblocking mode, or set the socket to block mode (the default). 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
Simple instance Service side

We use the socket function of the socket module to create a socket object. The socket object can set up a socket service by calling other functions.

We can now specify Port (port)of the service by invoking the bind (hostname) function.

Next, we call the accept method of the socket object. The method waits for the client to connect and returns a connection object that indicates that the client is connected.

The complete code for the service side (server.py) is as follows:

#!/usr/bin/env python#-*-coding:utf-8-*-"" "@Time: 2018/5/5 21:45   @Author: June Hong" "Import socket  # Import Socket Module SK = Socket.socket ()  # Create socket Object Sk.bind ((' 127.0.0.1 ', 9999)  # bound port, "127.0.0.1" on behalf of native address, 9999 set the port address for the link sk.listen (5)  # Set Listener, up to 5 clients to queue conn, addr = Sk.accept ()  # blocking state, passive waiting for client connection print (conn)  # Conn can understand the client's socket object Print (addr)  # addr for the client's port address Accept_data = CONN.RECV (1024x768)  # CONN.RECV () to receive the contents of the client, Received is bytes type data accept_data2 = str (accept_data, encoding= ' Utf-8 ')  # decoded with "Utf-8" Print (".". Join ("Receive content:", Accept_ DATA2, "Client port:", str (addr[1]))) Send_data = input (' Input send content: ') conn.sendall (bytes (send_data, encoding= ' Utf-8 '))  # Send content must be bytes type data, bytes (data,encoding= ' utf-8 ') encoded in "UTF8" format conn.close ()
Client

Next we write a simple client instance that connects to the service created above. The port number is 8888.

The socket.connect (hosname, Port) method opens a TCP connection to a service provider that hosts a port of "127.0.0.1" . After the connection we can start from the service end of the data, remember that the operation will need to close the connection after completion.

The complete code for the client (client.py) is as follows:

#!/usr/bin/env python#-*-coding:utf-8-*-"" "@Time: 2018/5/5 22:08   @Author: June Hong" "Import Socketsk = Socket.sock ET () sk.connect (' 127.0.0.1 ', 9999)  # actively initializes the connection to the server side send_data = input (' Input send content: ') sk.sendall (bytes (Send_data, encoding= ' Utf-8 ')) Accept_data = Sk.recv (1024x768) print (str (accept_data, encoding= ' Utf-8 ')) Sk.close ()

Above just realize the service side of the receive and send, below we upgrade can continue to communicate:

Service side

The server-side (server1.py) complete code is as follows:

Import socket

SK = Socket.socket ()
Sk.bind (' 127.0.0.1 ', 9988)
Sk.listen (5)
While True:
conn, addr = Sk.accept ()
While True:
Accept_data = str (CONN.RECV (1024x768), encoding= ' Utf-8 ')
Print (". Join" ([' Receive content: ', Accept_data, ' Client port: ', str (addr[1])])
if Accept_data = = ' Byebye ': # If you receive "Byebye", jump out of Loop end and first client communication and start communicating with the next client
Break
Send_data = input ("Input send content:")
Conn.sendall (Bytes (send_data, encoding= ' Utf-8 '))
Conn.close () # end communication when jumping out of a loop
Client

The complete code for the client (client1.py) is as follows:

Import Socketsk = Socket.socket () sk.connect ((' 127.0.0.1 ', 9988)      # actively initializes the connection to the server while True:    send_data = Input (' Input send content: ')    sk.sendall (bytes (send_data,encoding= ' UTF8 '))    if send_data = = ' Byebye ': Break    accept_data = str (SK.RECV (1024x768), encoding= ' UTF8 ')    print ('. Join (' Receive content: ', accept_data)) Sk.close ()

In the above simple example, the client must be queued to communicate with the server, only the current customer after the end of communication with the server to communicate with the service, then there is no way to allow multiple clients to communicate with the server at the same time? Then we need to use the Socketserver module:

Simple concurrent instance Service side
Import Socketserver # Imports Socketserver Module class MyServer (Socketserver. Baserequesthandler): # Create a class that inherits from the Baserequesthandler class Def handle (self) under the Socketserver module: # to implement a concurrency effect you must override the handler method in the parent class, where The logical code of the service side is implemented in the method (no further write connection preparation, including bind (), listen (), accept () method) while 1:conn = self.request addr = Self . client_address # above two lines of code, equal to CONN,ADDR = Socket.accept (), but in the Socketserver module has been packaged for us, but also for us packaging including bind (), listen (), AC Cept () method while 1:accept_data = str (CONN.RECV (1024x768), encoding= ' UTF8 ') print (accep T_data) If Accept_data = = "Byebye": Break send_data = bytes (Input (' >&G T;>>> '), encoding= ' UTF8 ') conn.sendall (send_data) conn.close () if __name__ = = ' __main__ ' : # Incoming port address and our newly created Baserequesthandler class instantiation Object sever = Socketserver, inherited from the Socketserver module. Threadingtcpserver ((' 127.0.0.1 ', 9977), MyServer) Sever.serve_forever () # Activates the server by calling the object's Serve_forever () method
Client
Import Socketsk = Socket.socket () sk.connect ((' 127.0.0.1 ', 9977)  # Active initialization and server-side connection while True:    send_data = input ( ' Input send content: ')    sk.sendall (bytes (send_data, encoding= ' UTF8 '))    if send_data = = ' Byebye ': Break    Accept_ data = str (SK.RECV (1024x768), encoding= ' UTF8 ')    print ('. Join (' Receive content: ', Accept_data) ') Sk.close ()

 

Python3 Socket Network Programming

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.