"Python" Socket Network programming

Source: Internet
Author: User

Python3 Network Programming

"Either Str2bytes or BYTES2STR is encoded in Utf-8str (   , encoding= ' utf-8 ') bytes (   , encoding= ' Utf-8 ') while in use. Encode (' Utf-8 '), although the type is byte, it often "

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 creates socket## 2 server for socket-bound IP address and port number based on address type (IPV4,IPV6), socket type, protocol # # 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 point 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 successful, send connection status information to the server # # 8 The server Accept method returns, Successful Connection # # 9 The client writes information to the socket (or writes information to the socket) # # 10 Server Read information (client read information) # # 11 Client off # # 12 Server side off

Socket object (built-in) method server side
S.bind ()   # binds the address (host,port) to the socket, and 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
Client
S.connect ()   # actively Initializes 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 instead of throwing an exception when an error occurs
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 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 ExampleServer we use the socket module Socketfunction 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 is as follows:
Import Socket  # importing Socket module
SK = Socket.socket () # Create socket Object Sk.bind (("127.0.0.1", 8888) # bound port, "127.0.0.1" for native address, 8888 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 # <socket.socket fd=4, Family=addressfamily.af_inet, Type=socketkind.sock_stream, Proto=0, Laddr= (' 127.0.0.1 ', 9005), raddr= (' 127.0.0.1 ', 36694) >print (addr) # addr for the client's port address # (' 127.0.0.1 ', 40966) accept _data = Conn.recv (1024x768) # CONN.RECV () receives the contents of the client, receives the bytes type data, Accept_data2 = str (accept_data, encoding= "UTF8") # str (data,encoding= "UTF8") uses "UTF8" to decode print ("". Join (("Receive content:", Accept_data2, " Client port:", str (addr[1]))) Send _data = input ("Input send content:") Conn.sendall (bytes (send_data, encoding= "UTF8")) # Send content must be bytes type data, bytes (data, encoding= "UTF8") encoded in "UTF8" format conn.close ()

The client next we write a simple client instance connected 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 is as follows:
Import Socketsk = Socket.socket () sk.connect (("127.0.0.1", 8888)  # Active initialization of connection to server side Send_data = input ("Input send content:") Sk.sendall (Bytes (send_data, encoding= "UTF8")) Accept_data = Sk.recv (1024x768) print (str (accept_data, encoding= "UTF8")) Sk.close ()
Service side
Import Socketsk = Socket.socket () sk.bind (("127.0.0.1", 9008)) Sk.listen (5) while True:    conn, addr = sk.accept ()    While True:        accept_data = str (CONN.RECV (1024x768),                          encoding= "UTF8")        print ("". Join (["Receive content:", Accept_data, "    client port: ", str (addr[1]        ))) if Accept_data = = "Byebye":  # If you receive "Byebye" then jump out of the loop and communicate with the first client, start communicating with the next client break        send_data = input (" Input send inside P capacity: ")        Conn.sendall (bytes (send_data, encoding=" UTF8 "))    Conn.close ()  # end communication when jumping out of the loop
Client
Import Socketsk = Socket.socket () sk.connect (("127.0.0.1", 9008)  # Active initialization with server-side connection while True:    send_data = Input ("Enter 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 InstancesService 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 our packaging including bind (), listen (), a Ccept () method while 1:accept_data = str (CONN.RECV (1024x768), encoding= "UTF8") print (ACCE Pt_data) If Accept_data = = "Byebye": Break send_data = bytes (Input (">& Gt;>>> "), encoding=" UTF8 ") Conn.sendall (Send_data) conn.close () if __name__ = = ' __main__ ': Sever = socketserver. Threadingtcpserver (("127.0.0.1", 8888), MyServer) # Incoming port address and our new inherit from Socketse Baserequesthandler class instantiation objects under the RVer module sever.serve_forEver () # activates the server by invoking the Serve_forever () method of the object 
Client
Import Socketsk = Socket.socket () sk.connect (("127.0.0.1", 8888)  # Active initialization of connection to 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 ()

"Python" Socket Network 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.