Python Network programming and sockets

Source: Internet
Author: User

2017-07-24 20:43:49

The socket is also called a socket, and the application usually makes a request to the network through a "socket" or answers a network request. The main operational flow of the HTTP protocol is request-response, which is the request response. We can use the socket library in Python to build the connection, and then use the Get method to get the server-side data.

First, use the socket to get the Web page

ImportSocket#socket parameter declaration, without modification directly usingMysock =Socket.socket (Socket.af_inet,socket. SOCK_STREAM)#Establish socket connection, address plus port numberMysock.connect (('www.py4inf.com', 80))#According to the requirements of the HTTP protocol, the information sent must start with get, followed by the URL address + protocol + two line break, and finally because it is py3, so need to add encode ()Mysock.send ('GET http://www.py4inf.com/http/1.1\n\n'. Encode ()) whileTrue:#because it is py3, we need to add decode ()data = MYSOCK.RECV (512). Decode ()ifLen (data) <1:         Break    Print(data) mysock.close ()

Second, use the request library for network connection

This is very convenient, do not directly with the transport layer socket, directly to the URL of the GE method.

Import= requests.get ('http://jwc.seu.edu.cn/')  Print(r.text)

Python Network programming and sockets

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.