As a PHP programmer, but also interested in the network, PHP compared to the egg pain, so I took some time to see Python
Before Learning Python Foundation for work reasons, intermittent to see a foundation, almost can write code
Recently, I was looking at the basics of Python network programming, and was prepared to learn by practicing, copying an example of a book.
Code that runs under the CLI
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 #^ Set Encoding: Noon in code will cause compilation errors4 5 #Introducing the Socket,sys module6 ImportSocket,sys7 8 #receive parameters passed by the CLI (service name)9Ser_name = sys.argv[1]Ten One Print "Creating Socket ..." A #Create socket -s =Socket.socket (Socket.af_inet,socket. SOCK_STREAM) - Print "Dine." the - Print "looking up port number ..." - - #Exception capture: The service name passed by the CLI may be incorrect for this exception handling + Try: - #get the port number by service name and reply type +Port = Socket.getservbyname (Ser_name,'TCP') A exceptSocket.error as E: at #Exception - Printe -Sys.exit (1) - - Print "Done ." - in Print "Connect to remote host%d ..."%Port - to #catch Exception: The server may not have the corresponding service turned on, or the network problem causes the connection failure to occur unexpectedly + Try: - #connecting to the service side theS.connect (("www.baidu.com", port)) * exceptSocket.error as E: $ #ExceptionPanax Notoginseng Print "Strange Error creating socket:%s"%e -Sys.exit (1) the + Print "Done ." A the #information that can be obtained when a connection is successfully established + #client-initiated connection IP and port - Print "Connect from", S.getsockname () $ #IP acquisition ports on the server side $ Print "Connect to", S.getpeername ()
Python network programming, obtaining port numbers through service names and session types (TCP,UDP), simple exception handling