**. Python's Path to self-study: Network programming

Source: Internet
Author: User

Socket

Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and are a handle to a chain of communication, where applications usually make requests to the network through "sockets" or respond to network requests.

1. First look at the simple version of the client and server building

Client

#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketip_port= ('127.0.0.1', 9999)#test address and PortSK= Socket.socket ()#Generate HandleSk.connect (Ip_port)#connecting to a serversk.sendall (Bytes ('... .. connecting ...','UTF8'))#Python3 sending data in a wordserver_reply = SK.RECV (1024)#receiving data from the serverPrint(Str (server_reply,'UTF8'))#The output is in string formsk.close ()

Server

#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketip_port= ('127.0.0.1', 9999) SK= Socket.socket ()#Generate HandleSk.bind (Ip_port)#binding IP addresses and portsSk.listen (5)#listening, 5 is the maximum number of connections whileTrue:Print('... server waiting ...') conn, addr= Sk.accept ()#block pending connection, generate instance conn, and return instance and addressClient_data= CONN.RECV (1024)#receive instance data, 1024 characters    Print(Str (Client_data,'UTF8')) Conn.sendall (bytes ('... connect successfully ...','UTF8'))#data sent back by the serverconn.close ()

2. Improvement: The above example can only achieve one-time communication, we improve the motivation is to complete a similar to QQ chat interactive communication

Client

ImportSocketip_port= ('127.0.0.1', 9999)SK=Socket.socket () sk.connect (ip_port) sk.sendall (bytes ('Request Communication','UTF8')) Server_reply= SK.RECV (1024)Print(Str (server_reply,'UTF8')) whileTrue:#Interactive CommunicationUserinput = input (">>:"). Strip () sk.send (bytes (userinput,'UTF8')) Server_reply= SK.RECV (1024)    Print(Str (server_reply,'UTF8') ) Sk.close ()

Server

#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketip_port= ('127.0.0.1', 9999) SK=Socket.socket () sk.bind (Ip_port) Sk.listen (5) whileTrue:Print('Server Waiting ...') conn, addr=sk.accept () client_data= CONN.RECV (1024)    Print(Str (Client_data,'UTF8')) Conn.sendall (bytes ('Connection Successful','UTF8'))     whileTrue:client_data= CONN.RECV (1024)        Print(Str (Client_data,'UTF8')) Server_response= Input ("\033[32;1m>>:\033[0m"). Strip () conn.send (bytes (server_response)) Conn.close ()

3. Improvement: Implement server Exception handling in multi-connection situations

Client

ImportSocketip_port= ('127.0.0.1', 9999) SK=Socket.socket () sk.connect (ip_port) sk.sendall (bytes ('Request Communication','UTF8')) Server_reply= SK.RECV (1024)Print(Str (server_reply,'UTF8')) whileTrue:userinput= Input (">>:"). Strip () sk.send (bytes (userinput,'UTF8')) Server_reply= SK.RECV (1024)    Print(Str (server_reply,'UTF8') ) Sk.close ()

Server

#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketip_port= ('127.0.0.1', 9999) SK=Socket.socket () sk.bind (Ip_port) Sk.listen (5)  whileTrue:Print('Server Waiting ...') conn,addr=sk.accept () client_data= CONN.RECV (1024)      Print(Str (Client_data,'UTF8')) Conn.sendall (bytes ('Don't answer, don't answer , don't answer','UTF8'))     whileTrue:Try: Client_data= CONN.RECV (1024)            Print(Str (Client_data,'UTF8'))        exceptException:Print("Connection Break!!!")             Breakconn.send (Client_data) conn.close ()#While True:linux version#Client_data = conn.recv (1024x768)#print ("recv:", str (client_data, ' UTF8 '))#If not client_data:break#conn.send (client_data)

4. SSH communication on Linux: solving Big Data transfers

Client:

#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketip_port= ('127.0.0.1', 9999) SK=Socket.socket () sk.connect (Ip_port) whileTrue:user_input= Input ("Cmd>>:"). Strip ()ifLen (user_input) = = 0:Continue        ifUser_input = ='Q': Breaksk.send (Bytes (user_input,'UTF8'))        #ack_msg = B "cmd_result_size|%s"% len (cmd-result)server_ack_msg = SK.RECV (100) cmd_res_msg= str (server_ack_msg). Split ("|")        ifCmd_res_msg[0] = ="cmd_result_size": Cmd_res_size= Int (cmd_res_msg[1]) Sk.send (b"Client_ready_to_recv") Res="'rec_size=0 whileRec_size <=Cmd_res_size:data= SK.RECV (500) Rec_size+ = Len (data)#Actual SizeRes + =Str (Data.decode ())Else:                Print(str (res))Print("... recv done ....") Sk.close ()

Service side:

#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketImport TimeImportSubprocessip_port= ('127.0.0.1', 9999) SK=Socket.socket () sk.bind (Ip_port) Sk.listen (5) whileTrue:Print('Server Waiting ...') conn,addr=sk.accept () whileTrue:client_data= CONN.RECV (1024)           if  notClient_data: Break           Print("recv:", str (Client_data,'UTF8')) cmd= STR (Client_data,"UTF8"). Strip () Cmd_call= Subbprocess. Popen (Cmd,shell=true, stdout=subprocess. PIPE) Cmd_result=Cmd_call.stdout.read ()ifLen (cmd_result) = =0:cmd_result= b"cmd execution has no output:"ack_msg= b"cmd_result_size|%s"%Len (cmd_result) conn.send (ack_msg) conn.recv (10)#generate blocking, split two times send, avoid, two separate data sent out together.            ifClient_ack.decode () = ='Clent_ready_to_recv': Conn.send (Cmd_result)#but this way, the CPU wastes a lot of timeConn.close ()

**. Python's Path to self-study: 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.