1. 程式人生 > >Python之socket程式設計淺談

Python之socket程式設計淺談

"""

<axiner>宣告:
(錯了另刂扌丁我)
(如若有誤,請記得指出喲,謝謝了!!!)

"""

以下是維基百科的解釋:
A network socket is an internal endpoint for sending or receiving data at a single node in a computer network. Concretely, it is a representation of this endpoint in networking software (protocol stack), such as an entry in a table (listing communication protocol, destination, status, etc.), and is a form of system resource.

個人總結:
簡單說,socket就是通訊鏈中的控制代碼;通俗說,就是資源識別符號;再俗點,就是手機號。

可以把socket看成為`特殊檔案`,該檔案就是`服務端`和`客戶端`。
socket的程式設計就是`對檔案的操作`
檔案的操作:開啟--處理(讀寫)--關閉
所以:
socket的操作:
注:`處理`之前的可以看成為`開啟檔案`
server端:例項化--bind--listen--處理(accept為阻塞)--close
client端:例項化--connect--處理(recv為阻塞)--close




=================================================================

 

eg:(Python27)

 

# server端:  
import socket  
  
sk = socket.socket()  
sk.bind(('127.0.0.1', 8080))  
sk.listen(5)  
  
while True:  
    conn, address = sk.accept()  
    # ...  
  
sk.close()  
  
# -------------------------------  
#client端:  
import socket  
  
obj = socket.socket()  
obj.connect(('127.0.0.1', 8080))  
  
while True:  
    obj.recv(1024)  
    # ...  
  
obj.close()