Python network Programming--Client

Source: Internet
Author: User

The basic interface of network communication is the socket, which expands the basic I/O to network communication of the operating system. The socket can be established via the socket () function to connect via the Connect () function. The socket can be used to determine the IP address and port number of the local and remote endpoints. Sockets are a common interface for different protocols, and can handle both TCP and UDP traffic.

Creating a socket requires two steps: Setting up a Socket object, connecting to a remote server

ImportSocketPrint "Creating Socket"s=Socket.socket (socket.af_inet, socket. SOCK_STREAM) #指明通信类型和协议家族Print "done!"Print "connecting to remote host ..."S.connect (("www.baidu.com", 80))Print " Done"

Run results

Creating socketdone! Connecting to remote host ... Done

Find Port number

Find the port number by protocol name and port name (Unix system can find the corresponding port number in etc/services)

ImportSocketPrint "Creating Socket"s=Socket.socket (socket.af_inet, socket. SOCK_STREAM)Print "done!"Print "looking up port number ..."Port= Socket.getservbyname ("http","TCP")PrintPortPrint "done!"Print "connecting to remote host ..."S.connect (("www.baidu.com", port))Print "done!!"

Run results

Creating socketdone! Looking up port number ... 80done! Connecting to remote host ... done!!

Getting information from the socket

ImportSocketPrint "Creating Socket"s=Socket.socket (socket.af_inet, socket. SOCK_STREAM)Print "done!"Print "looking up port number ..."Port= Socket.getservbyname ("http","TCP")PrintPortPrint "done!"Print "connecting to remote host ..."S.connect (("www.baidu.com", port))Print "done!!"Print "Connected from", S.getsockname () #获得本地机器的ip和端口号 (the port number is randomly assigned by the operating system and is not the same every time) Print "Connected to", S.getpeername ()#获得连接机器的ip和端口号

One run result

Creating socketdone! Looking up port number ... 80done! Connecting to remote host ... done!! Connected from (' 192.168.209.129 ', 56245) Connected to (' 220.181.112.244 ', 80)

Using socket communication

Socket object: Send (), sendto (), recv (), Recvfrom ()

File class object: Read (), write (), ReadLine ()

Handling Errors

Importsocket, Syshost= Sys.argv[1]textport= Sys.argv[2]filename= Sys.argv[3]Try: S=Socket.socket (socket.af_inet, socket. SOCK_STREAM)exceptSocket.error, E:Print "Strange Error creating socket:%s"%e Sys.exit (1)Try: Port=Int (textport)exceptValueError:Try: Port= Socket.getservbyname (Textport,'TCP')    exceptSocket.error, E:Print "couldn ' t find your port:%s"%e Sys.exit (1)Try: S.connect ((host, port))exceptSocket.gaierror, E:Print "address-related Error connecting to server:%s"%e Sys.exit (1)exceptSocket.error, E:Print "Connection Error:%s"%e Sys.exit (1)Try: S.sendall ("GET%s http/1.0\r\n\r\n"%filename)exceptSocket.error, E:Print "Error sending data:%s"%e Sys.exit (1)Print "---------------------------------------" while1:    Try: buf= S.RECV (2048)    exceptSocket.error, E:Print "========error receving data:%s======="%e Sys.exit (1)    if  notLen (buf): Breaksys.stdout.write (BUF)Print "---------------------------------------"

Improved

#Coding:utf-8ImportSocketImportSYSImportTimehost= Sys.argv[1]textport= Sys.argv[2]filename= Sys.argv[3]Try: S=Socket.socket (socket.af_inet, socket. SOCK_STREAM)exceptSocket.error, E:Print "Strange Error creating socket:%s"%e Sys.exit (1)Try: Port=Int (textport)exceptValueError:Print "ValueError"    Try: Port= Socket.getservbyname (Textport,'TCP')    exceptSocket.error, E:Print "couldn ' t find your port:%s"%e Sys.exit (1)Try: S.connect ((host, port))exceptSocket.gaierror, E:#host name is not correct    Print "address-related Error connecting to server:%s"%e Sys.exit (1)exceptSocket.error, E:#There is a problem connecting to the remote host    Print "Connection Error:%s"%e Sys.exit (1)Print "sleepping ....."Time.sleep (10)Print "continuing."Try: S.sendall ("GET%s http/1.0\r\n\r\n"%filename)exceptSocket.error, E:Print "Error sending data:%s"%e Sys.exit (1)Try: S.shutdown (1)exceptSocket.error, E:Print "Error sending data (detected by shutdown):%s"%e Sys.exit (1)    Print "---------------------------------------" while1:    Try: buf= S.RECV (2048)        Print "Try"    exceptSocket.error, E:Print "========error receving data:%s======="%e Sys.exit (1)    if  notLen (BUF):#accepted as empty        Print " Break"         Breaksys.stdout.write (BUF)Print "---------------------------------------"

Python network Programming--Client

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.