一、什麼是socket?
python 官方關於 socket 的函式請看
socket通常也稱作"套接字",用於描述ip位址和埠,是乙個通訊鏈的控制代碼,應用程式通常通過"套接字"向網路發出請求或者應答網路請求。
socket起源於unix,而unix/linux基本哲學之一就是「一切皆檔案」,對於檔案用開啟、讀寫、關閉模式來操作。socket就是該模式的乙個實現,socket即是一種特殊的檔案,一些socket函式就是對其進行的操作(讀/寫io、開啟、關閉)
file模組是針對某個指定檔案進行開啟、讀寫、關閉
socket模組是針對 伺服器端 和 客戶端socket 進行開啟、讀寫、關閉
二、舉個例項
1執行結果如下:#!/usr/bin/env python2#
_*_ coding: utf-8 _*_3#
author:taoke
4import
socket
5import
sys6
try:7#
建立socket
8 s =socket.socket(socket.af_inet,socket.sock_stream)
9except
socket.error:10#
建立失敗,產生socket.error異常
11print("
socket creat error:
"+str(socket.error))
12sys.exit()
1314
print("
creat socket")
15 host = '
www.oschina.net'16
17try:18
#獲取主機ip
19 remote_ip =socket.gethostbyname(host)
20except
socket.gaierror:
21print("
hostname could not be resolved,exiting")
22sys.exit()
23print("
ip address of
"+host+"
is "+remote_ip)
24 port = 8025#
連線26
關閉socket
46 s.close()
tcp客戶端:
1 建立套接字,連線遠端位址
# socket.socket(socket.af_inet,socket.sock_stream) , s.connect()
2 連線後傳送資料和接收資料
# s.sendall(), s.recv()
3 傳輸完畢後,關閉套接字
#s.close()
Python Socket 程式設計
client import socket,sys if name main 處理引數 argv sys.argv if len argv 3 or len argv 2 and argv 1 print useage argv 0 sys.exit 0 host argv 1 server ip位址...
python socket程式設計
python 編寫server的步驟 1.第一步是建立socket物件。呼叫socket建構函式。如 socket socket.socket family,type family引數代表位址家族,可為af inet或af unix。af inet家族包括internet位址,af unix家族用於...
python socket程式設計
客戶端 author lenovo fromsocketimport host localhost port 2157 bufsize 1024 addr host,port tcpclient socket af inet,sock stream tcpclient.connect addr wh...