python網絡編程:一、前言及socket初探


在知乎上看到有人提問, Python 網絡編程需要學習哪些網絡相關的知識?,看了下,覺得還挺有道理。主要的觀點如下:
 
Python網絡編程是一個很大的范疇,個人感覺需要掌握的點有:  
  1. 如何使用Python來創建socket, 如何將socket與指定的IP地址和端口進行綁定,使用socket來發送數據,接受數據, 
  2. 如何使用Python中處理線程,從而編寫可以同時處理多個請求的web服務器 
  3.  如何使用Python來控制HTTP層的邏輯,包括如何創建http GET,POST,PUT,DELETE請求,如何處理接受到的HTTP請求,這些分別涉及python的httplib, basehttpserver等模塊    
  4. 掌握一種基本的python的web開發框架,比如webpy, django,pylon 
  5.  了解非阻塞式的HTTP Server,比如tornado 
  6. 了解twisted, python編寫的消息驅動的網絡引擎 
 
參考資料:
網絡基礎知識
  1. HTTP: the definitive guide http://www.amazon.com/HTTP-Definitive-Guide-David-Gourley/dp/1565925092/
  2. Computer Networking: A Top-Down Approach http://www.amazon.com/Computer-Networking-Top-Down-Approach-Edition/dp/0136079679/ref
 
python 網絡編程基礎         
  1. python 網絡編程 http://www.amazon.com/Foundations-Python-Network-Programming-Goerzen/dp/1590593715 
  2. python socket編程的文檔 http://docs.python.org/library/socket.html 
  3. python httplib的文檔 http://docs.python.org/library/httplib.html
 
python常用框架文檔:          
  1. django 的官方網站 https://www.djangoproject.com/ 
  2. twisted 的官方網站 http://twistedmatrix.com/trac/ 
  3. tornado 的官方網站 http://www.tornadoweb.org/
 


 
學了一下python的socket
 
socket概念:
      通常也稱作"套接字",用於描述IP地址和端口,是一個通信鏈的句柄。在Internet上的主機一般運行了多個服務軟件,同時提供幾種服務。每種服務都打開一個Socket,並綁定到一個端口上,不同的端口對應於不同的服務。Socket正如其英文原意那樣,象一個多孔插座。一台主機猶如布滿各種插座的房間,每個插座有一個編號,有的插座提供220伏交流電, 有的提供110伏交流電,有的則提供有線電視節目。 客戶軟件將插頭插到不同編號的插座,就可以得到不同的服務。
 
主要用到的模塊: socket
  • 建立新的socket:socket.socket([family[type[proto]]])
  • 獲取遠程服務器ip:socket.gethostbyname(host)
  • 連接到一個遠程套接字地址:socket.connect(address) 
  • 向socket發送數據:socket.sendall(string[, flags]) 
  • 從socket接受數據:socket.recv(bufsize[, flags]) 
  • Bind the socket to address.: socket.bind(address) 
  • Listen for connections made to the socket. :socket.listen(backlog) 
 
以下代碼主要參考這個教程: http://www.binarytides.com/python-socket-programming-tutorial/
客戶端:
 
 1 # clientsocket.py
 2 
 3 import socket
 4 
 5 def Main():
 6     try:
 7         # Address Family : AF_INET (this is IP version 4 or IPv4)
 8         # Type :  SOCK_STREAM (this means connection oriented TCP protocol)
 9         #         SOCK_DGRAM indicates the UDP protocol. 
10         new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
11     except socket.error, msg:
12         print 'Failed to creat socket. Error code:', str(msg[0]), 
13         print 'Error message:', msg[1]
14         return
15     print 'Socket Created'
16     
17     host = 'www.baidu.com'
18     port = 80
19     try:
20         remote_ip = socket.gethostbyname(host)
21     except socket.gaierror:
22         print 'Hostname could not be resolved. Exiting.'
23         return 
24     print 'Ip address of', host, 'is', remote_ip
25     
26     # Connect to remote server
27     new_socket.connect((host, port))
28     print 'Socket Connected to', host, 'on ip', remote_ip
29     
30     # Send some data to remote server | socket.sendall(string[, flags]) 
31     message = 'GET / HTTP/1.1\r\n\r\n'
32     try:
33         new_socket.sendall(message)
34     except socket.error:
35         print 'Send fail.'
36         return 
37     print 'Message send successfully.'
38 
39     # Receive data | socket.recv(bufsize[, flags]) 
40     reply = new_socket.recv(4096)
41     print reply
42     
43     # Close the socket
44     new_socket.close()
45     
46     
47 if __name__ == '__main__':
48     Main()

 

服務器端:
 
  • Bind the socket to address.: socket.bind(address) 
  • Listen for connections made to the socket. :socket.listen(backlog) 
#! /usr/bin/env python

# serversockethand.py

"""
To handle every connection we need a separate handling code to run along 
with the main server accepting connections. One way to achieve this is 
using threads. The main server program accepts a connection and creates
a new thread to handle communication for the connection, and then the
 server goes back to accept more connections.
"""

import socket
import thread

def Main():
    HOST = ''
    PORT = 8888
    
    new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print 'Socket created.'
    
    # Bind socket to local host and port 
    try:
        new_socket.bind((HOST, PORT))
    except socket.error, msg:
        print 'Bind failed. Error code:', str(msg[0]) + 'Message' + msg[1]
        return 
    print 'Socket bind complete'

    # Listening on socket
    new_socket.listen(10)
    print 'Socket now listening..'
    
    # Now keep talking with client
    while 1:
        # Wait to accept a connection 
        conn, addr = new_socket.accept()
        print 'Connected with', addr[0], ':', str(addr[1])
        
        thread.start_new_thread(clientThread, (conn, ))
    
    new_socket.close()
    
    
# Function for handling connections. This will be used to create threads.
def clientThread(conn):
    # Sending message to connected client
    conn.send('Welcome to the server. Type something and hit enter\n')
    
    while 1:
        data = conn.recv(1024)
        if not data:
            break
        reply = 'OK..' + data
        conn.sendall(reply)
    
    conn.close()
    

if __name__ == '__main__':
    Main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM