Python - access network

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 socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect('host', 'port number')
mysock.connect( ('www.py4inf.com', 80) )

# send our request, ask for some webpage
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')

# receive data
while True:
    data = mysock.recv(512)
    if ( len(data) < 1 ) :
        break
    print data
# don't forget to close the socket
mysock.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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章