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 lib 11 from socket import socket, AF_INET, SOCK_STREAM 12 import sys 13 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 socket 30 #端口号为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 #缓冲区为1k 34 35 36 def bulidConnect( self ): 37 ‘‘‘ 38 建立连接,获取连接客户端的信息,接收数据 39 ‘‘‘ 40 tcpClientSocket, addr = self.tcpServerSocket.accept() 41 print ‘conn from : ‘, addr 42 raw_data = tcpClientSocket.recv( int(self.buffer_size) ) 43 print ‘receive data : ‘, raw_data 44 45 return ( tcpClientSocket, raw_data ) 46 47 48 def process( self, data ): 49 ‘‘‘ 50 socket传输的数据加工处理,继承重写该函数 51 ‘‘‘ 52 result = data 53 return result 54 55 56 def send( self, tcp, result ): 57 ‘‘‘ 58 返回信息,关闭连接 59 ‘‘‘ 60 tcpClientSocket = tcp 61 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".‘ % message 11 12 sock.send( ‘[{"url":"www.baidu.com"}]‘ ) 13 print ‘receive from server : ‘, sock.recv(1024) 14 15 sock.close() 16 print ‘Closing socket.‘
时间: 2024-10-03 22:53:47