socket(套接字),传输层通信的端点,由IP和端口号组成(IP,Port),可以通过socket精确地找到服务器上的进程并与之通信
python2.6实现,基于AF_INET(网络套接字)
类型SOCKET_STREAM(TCP套接字),SOCKET_DGRAM(UDP套接字)
TCP socket通信逻辑
TCP服务端:创建socket>>>绑定本地服务器>>>监听连接>>>通信交互>>>关闭连接
TCP客户端:创建socket>>>与服务器建立连接>>>通信交互>>>关闭连接
Python Tcp Socket服务端
#!/usr/bin/python
#-*-coding:utf-8-*- # filename : Tdpsocket.py
# author :
# create date : 2015-03-25
# modify date :
# description : tcp socket #import stander lib
from socket import socket, AF_INET, SOCK_STREAM
import sys
sys.path.append( '..' ) class Tcpsocket():
'''
Tcpsocket类,建立tcp socket服务端,获得建立连接的配置信息
用法:
p = Tcpsocket.Tcpsocket()
p.listen()
无限循环监听端口,process重写数据处理方式
''' def __init__( self ):
'''
初始化,建立socket,ip端口绑定
'''
self.tcpServerSocket = socket( AF_INET, SOCK_STREAM ) #创建TCP socket
#端口号为0-65535,0-1023为系统保留,动态端口49152-65535,服务使用端口为1024-49151区间
self.tcpServerSocket.bind( ('127.0.0.1', 20015) )
self.tcpServerSocket.listen(5)
self.buffer_size = 1024 #缓冲区为1k def bulidConnect( self ):
'''
建立连接,获取连接客户端的信息,接收数据
'''
tcpClientSocket, addr = self.tcpServerSocket.accept()
print 'conn from : ', addr
raw_data = tcpClientSocket.recv( int(self.buffer_size) )
print 'receive data : ', raw_data return ( tcpClientSocket, raw_data ) def process( self, data ):
'''
socket传输的数据加工处理,继承重写该函数
'''
result = data
return result def send( self, tcp, result ):
'''
返回信息,关闭连接
'''
tcpClientSocket = tcp
tcpClientSocket.send( result )
tcpClientSocket.close() def listen( self ):
'''
监听端口,无限循环
'''
while True:
print 'wati for connect:'
socket_data = self.bulidConnect() #建立连接
result = self.process( socket_data[1] ) #接收信息,处理信息
self.send( socket_data[0], result ) #向客户端返回信息
self.close() def close( self ):
'''
关闭连接
'''
self.tcpServerSocket.close() def __del__( self ):
self.close() if __name__ == '__main__':
p = Tcpsocket()
p.listen()
Python Tcp Socket客户端
import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ( '127.0.0.1', 20015 ) print 'Connecting to %s:%s.' % server_address
sock.connect(server_address) message = "I'm TCP client"
print 'Sending "%s".' % message sock.send( '[{"url":"www.baidu.com"}]' )
print 'receive from server : ', sock.recv(1024) sock.close()
print 'Closing socket.'