標籤:基本使用 cli cte send 服務 imp 客戶 ESS class
socket通常也叫做“通訊端”,用於串連server client,是一個通訊鏈的控制代碼,應用程式通常通過通訊端向網路發出請求或應答網路請求。
就像python 處理file一樣:
file是針對某個檔案 開啟-->讀寫-->關閉
socket是針對伺服器 用戶端進行 開啟-->讀寫-->關閉
server部分:
import socket,sysserver_address=(‘127.0.0.1‘, 8000)BUF_SIZE=1024try: server_sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) #建立新的socket對象except socket.error, msg: print "socket create fail, error code:" + str(msg[0]) + ‘error message:‘ + msg[1]print ‘socket create successfully‘try: server_sk.bind(server_address) #綁定server地址,address取決於地址族,AF_INET以元組表示except socket.error, msg: print "socket bind address error:" + str(msg[0]) + ‘error mssage:‘ + msg[1]print ‘socket bind address successfully‘server_sk.listen(5)print "listening..."while True: client_sk, client_addr = server_sk.accept() print "connected by:", client_addr while True: data=client_sk.recv(BUF_SIZE) print data client_sk.sendall(data)server_sk.close()
參數一:地址簇socket.AF_INET IPv4(預設)socket.AF_INET6 IPv6
參數二:類型socket.SOCK_STREAM 流式socket , for TCP (預設)socket.SOCK_DGRAM 資料報式socket , for UDP
Client部分:
import socket,sysserver_address=(‘127.0.0.1‘, 8000)BUF_SIZE=1024try: client_sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM)except socket.error, msg: print "socket create fail, error code:" + str(msg[0]) + ‘error message:‘ + msg[1]client_sk.connect(server_address)while True: data= raw_input(‘please input your sending message->‘) if not data: print "input data cannot be empty, please input again.." continue client_sk.sendall(data) recv_data = client_sk.recv(BUF_SIZE) print recv_dataclient_sk.close()
server 輸出:
socket create successfully
socket bind address successfully
listening...
connected by: (‘127.0.0.1‘, 63388)
aa
client 輸出:
please input your sending message->aa
aa
please input your sending message->
python socket 基本使用