The socket module in Python

Source: Internet
Author: User

python network programming without socket module

1. Simple use of the socket module to develop a simple command-line tool for example, as follows

1.1 Socket client-side code

1 #-*-coding:utf-8-*-2 #Author:wong Du3 4 ImportSocket5 6 #Create a Socket object7Client =Socket.socket ()8 #establish a connection to the server side9Client.connect (('localhost', 9494) )Ten  One  A  whileTrue: -     #Get user Input -Cli_send = input (">>:"). Strip () the     #Determine if user input is empty -     ifLen (cli_send) = =0: -         Continue -  +     #send data to server side, must be bytes type -Client.send (Cli_send.encode (encoding="Utf-8")) +  A     #receive server-side returned data, 102400 of the size of the received data atdata = CLIENT.RECV (102400) -     #to view the data received -     Print(Data.decode ()) -  - #Close Connection -Client.close ()

1.2 Socket server-side code

#-*-coding:utf-8-*-#Author:wong DuImportOSImportSocket#Create a socket connectionServer =Socket.socket ()#bind the appropriate IP and port numberServer.bind (('localhost', 9494) )#start listening, 5 to monitor the maximum number of connectionsServer.listen (5)Print("I'm going to start listening.")#wait for the request to connect, stuck; Conn is the connection object, addr is the connection identityPrint("waiting for client to request connection ~ ~") conn, addr=server.accept ()Print("Receive client connection, identity is:", addr) whileTrue:#receives the command sent by the client, 1024 is the size of the received datadata = CONN.RECV (1024)    #executes the command and receives the command to return the resultres =Os.popen (Data.decode ()). Read ()#if the command has no return result    if  notRes:res='Invalid command.'    #Send command return result to client, data must be bytes typeConn.send (Res.encode (encoding='Utf-8'))#Close ConnectionServer.close ()

The socket module in Python

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.