Python Network Programming second edition

Source: Internet
Author: User

Add a multi-process solution to the service side

1. Server-side code is as follows:

#!/usr/bin/python#!coding:utf-8ImportOs,sys,time fromSocketImport*defhandleclient (conn):Print '[INFO] handleclient is: {0}'. Format (Os.getpid ()) whileTrue:data= CONN.RECV (1024)        if  notData:Print '[INFO] handleclient client is stoped .'; Break        Print '[INFO] handleclient recive This----{0}'. Format (Data.encode ()) Reply='[INFO] handleclient the information from server to {0}'. Format (Data.decode ()) Conn.send (Reply.encode ()) Conn.close () os._exit (0)if __name__=="__main__": HostIP='127.0.0.1'Port=2048sock=socket (Af_inet,sock_stream) Sock.bind ((Hostip,port)) Sock.listen (5)    Print '[INFO] Parent pid is: {0} start listen {1}'. Format (Os.getpid (), (Hostip,port)) whiletrue:conn,addr=sock.accept ()Print '[INFO] Parent get a client {0}'. Format (addr) Cpid=os.fork ()ifCpid = = 0:handleclient (conn)

2, the client terminal code is as follows:

#!/usr/bin/python#!coding:utf-8 fromSocketImport*ImportOs,sysif __name__=="__main__":    #Defining Socketshostip='127.0.0.1'Port=2048sock=socket (af_inet,sock_stream) messages=['Hello I am a client'] Messages=messages+sys.argv[1:] Sock.connect ((hostip,port))Print '[INFO] already connected to server'         forMessageinchMessages:sock.send (Message.encode ())PrintSOCK.RECV (1024). Decode () Sock.close ()

Python Network Programming second edition

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.