標籤:
socket(通訊端),傳輸層通訊的端點,由IP和連接埠號碼組成(IP,Port),可以通過socket精確地找到伺服器上的進程並與之通訊
python2.6實現,基於AF_INET(網路通訊端)
類型SOCKET_STREAM(TCP通訊端),SOCKET_DGRAM(UDP通訊端)
TCP socket通訊邏輯
TCP服務端:建立socket>>>綁定本機伺服器>>>監聽串連>>>通訊互動>>>關閉串連
TCP用戶端:建立socket>>>與伺服器建立串連>>>通訊互動>>>關閉串連
Python Tcp Socket服務端
1 #!/usr/bin/python 2 #-*-coding:utf-8-*- 3 4 # filename : Tdpsocket.py 5 # author : 6 # create date : 2015-03-25 7 # modify date : 8 # description : tcp socket 9 10 #import stander lib11 from socket import socket, AF_INET, SOCK_STREAM12 import sys13 sys.path.append( ‘..‘ )14 15 16 class Tcpsocket():17 ‘‘‘18 Tcpsocket類,建立tcp socket服務端,獲得建立串連的配置資訊19 用法:20 p = Tcpsocket.Tcpsocket()21 p.listen()22 無限迴圈監聽連接埠,process重寫資料處理方式23 ‘‘‘24 25 def __init__( self ):26 ‘‘‘27 初始化,建立socket,ip連接埠綁定28 ‘‘‘29 self.tcpServerSocket = socket( AF_INET, SOCK_STREAM ) #建立TCP socket30 #連接埠號碼為0-65535,0-1023為系統保留,動態連接埠49152-65535,服務使用連接埠為1024-49151區間31 self.tcpServerSocket.bind( (‘127.0.0.1‘, 20015) )32 self.tcpServerSocket.listen(5)33 self.buffer_size = 1024 #緩衝區為1k34 35 36 def bulidConnect( self ):37 ‘‘‘38 建立串連,擷取串連用戶端的資訊,接收資料39 ‘‘‘40 tcpClientSocket, addr = self.tcpServerSocket.accept()41 print ‘conn from : ‘, addr42 raw_data = tcpClientSocket.recv( int(self.buffer_size) )43 print ‘receive data : ‘, raw_data44 45 return ( tcpClientSocket, raw_data )46 47 48 def process( self, data ):49 ‘‘‘50 socket傳輸的資料加工處理,繼承重寫該函數51 ‘‘‘52 result = data53 return result54 55 56 def send( self, tcp, result ):57 ‘‘‘58 返回資訊,關閉串連59 ‘‘‘60 tcpClientSocket = tcp61 tcpClientSocket.send( result )62 tcpClientSocket.close()63 64 65 def listen( self ):66 ‘‘‘67 監聽連接埠,無限迴圈68 ‘‘‘69 while True:70 print ‘wati for connect:‘71 socket_data = self.bulidConnect() #建立串連72 result = self.process( socket_data[1] ) #接收資訊,處理資訊73 self.send( socket_data[0], result ) #向用戶端返回資訊74 self.close()75 76 77 def close( self ):78 ‘‘‘79 關閉串連80 ‘‘‘81 self.tcpServerSocket.close()82 83 84 def __del__( self ):85 self.close()86 87 88 if __name__ == ‘__main__‘:89 p = Tcpsocket()90 p.listen()
Python Tcp Socket用戶端
1 import socket 2 3 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 4 server_address = ( ‘127.0.0.1‘, 20015 ) 5 6 print ‘Connecting to %s:%s.‘ % server_address 7 sock.connect(server_address) 8 9 message = "I‘m TCP client"10 print ‘Sending "%s".‘ % message11 12 sock.send( ‘[{"url":"www.baidu.com"}]‘ )13 print ‘receive from server : ‘, sock.recv(1024)14 15 sock.close()16 print ‘Closing socket.‘
Python Tcp Socket