Python - access network

来源:互联网 发布:java窗口程序实例 编辑:程序博客网 时间:2024/06/11 12:48

TCP Network

Transport Control Protocol(TCP) is built on top of IP.

TCP assumes IP might lose some data, so tcp will stores and retransmits data if it seems to be lost(when receive duplicate ACKs or ACK is time-out)

TCP will handle “flow control” using a transmit window (wnd)

TCP Connection / Sockets: network socket is an endpoint of a bidirectional inter-process communication flow.

TCP Port Number: a port is an application-specific software communications endpoint. It allows multiple networked applications to coexist on the same server.
Applications coexist at the same server
list of well-known port number


Sockets in Python

Python has built-in support for tcp sockets
import socket

import socketmysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# connect('host', 'port number')mysock.connect( ('www.py4inf.com', 80) )# send our request, ask for some webpagemysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')# receive datawhile True:    data = mysock.recv(512)    if ( len(data) < 1 ) :        break    print data# don't forget to close the socketmysock.close()

we can make HTTP easier with urllib


using urllib model

urllib can do all the sockets work for us and make web pages look like a file. In a word, it is more convenient.

Note: there are some differences between python2 and python3 when using urllib. Here, I use python3 as standard.

0 0
原创粉丝点击