Python 3 網路程式入門

 若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。


在介紹如何使用Python來開發網路程式之前,請讀者先複習相關的網路知識,此部份可參考筆者的文章:「網路程式開發者所需要的網路知識 ( Concepts for a network programmer )」。(題外話,若想用Java程式語言來開發網路程式的話,也可參考筆者的另一篇文章:「Java 網路程式入門 ( Java network programming )」)。本文示範的作業系統為Lubunt 18.10,所使用的開發工具為 VS Code(可參考筆者的兩篇文章:Python in Visual Studio CodeDebug Python Code in Visual Studio Code)。

網路程式通常會透過 Socket API 來撰寫,而Python的 socket 模組 提供了開發人員使用Socket的界面,這部份的細節請讀者閱讀參考資料。雖然Network Socket有幾種型態(底下文字取自 https://en.wikipedia.org/wiki/Network_socket#Types):
  • Raw sockets (or raw IP sockets), typically available in routers and other network equipment. Here the transport layer is bypassed, and the packet headers are made accessible to the application, and there is no port number in the address, just the IP address.
但本篇文章只針對 Stream socket 做範例說明,此範例的 Server 簡單地顯示有 Client 端連線進來,並回傳一則簡短訊息給 Client,之後就斷線了。當然實際的網路程式通常不會一連線就準備斷線。

Server 端的程式碼:
Client 端的程式碼:
Client 用的 Bash Script:

測試畫面:

從此範例可看出一些 TCP Socket 流程(見下圖)

此 TCP Socket 流程為開發網路程式的主要觀念之一,讀者要熟悉它喔。Python還有其他網路模組,此部份可參考 https://docs.python.org/3/library/internet.html。例如此指令「python -m webbrowser -t "http://yunlinsong.blogspot.com/"」就可以呼叫瀏覽器來開啟本部落格喔!有機會再來介紹如何用Python做個簡易的聊天室吧。

參考資料:
[1] https://www.tutorialspoint.com/python/python_networking.htm
[2] https://realpython.com/python-sockets/

沒有留言: