tornado做简单socket服务器(TCP)

http://blog.csdn.net/chenggong2dm/article/details/9041181

服务器端代码如下:

[python] view plaincopy
 
  1. #! /usr/bin/env python  
  2. #coding=utf-8  
  3.     
  4. from tornado.tcpserver import TCPServer    
  5. from tornado.ioloop  import IOLoop    
  6.     
  7. class Connection(object):    
  8.     clients = set()    
  9.     def __init__(self, stream, address):   
  10.         Connection.clients.add(self)   
  11.         self._stream = stream    
  12.         self._address = address    
  13.         self._stream.set_close_callback(self.on_close)    
  14.         self.read_message()    
  15.         print "A new user has entered the chat room.", address   
  16.         
  17.     def read_message(self):    
  18.         self._stream.read_until(' ', self.broadcast_messages)    
  19.     
  20.     def broadcast_messages(self, data):    
  21.         print "User said:", data[:-1], self._address  
  22.         for conn in Connection.clients:    
  23.             conn.send_message(data)    
  24.         self.read_message()    
  25.         
  26.     def send_message(self, data):    
  27.         self._stream.write(data)   
  28.             
  29.     def on_close(self):    
  30.         print "A user has left the chat room.", self._address  
  31.         Connection.clients.remove(self)    
  32.     
  33. class ChatServer(TCPServer):    
  34.     def handle_stream(self, stream, address):   
  35.         print "New connection :", address, stream   
  36.         Connection(stream, address)   
  37.         print "connection num is:", len(Connection.clients)  
  38.     
  39. if __name__ == '__main__':    
  40.     print "Server start ......"    
  41.     server = ChatServer()    
  42.     server.listen(8000)    
  43.     IOLoop.instance().start()   

经测试后发现,tornado的接收方法里,已经做了粘包处理。比如第18行的代码,就是用的tornado.iostream.BaseIOStream类的read_until(delimiter, callback) 方法。这个方法,将会从缓冲区里,直到读到截止标记(比如' '),就产生一次回调。如果没有截止标记,缓冲区就攒数据,直到等到截止标记出现,才会产生回调。看了一下源码,缓冲区默认是max_buffer_size=104857600 。

下面是客户端代码:

[python] view plaincopy
 
  1. #! /usr/bin/env python  
  2. #coding=utf-8  
  3.   
  4. import socket  
  5. import time  
  6.   
  7. HOST = '127.0.0.1'    # The remote host  
  8. PORT = 8000           # The same port as used by the server  
  9. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
  10. s.connect((HOST, PORT))  
  11.   
  12. s.sendall('Hello,  w')  
  13. time.sleep(5)  
  14. s.sendall('ord!  ')  
  15.   
  16. data = s.recv(1024)  
  17.   
  18. print 'Received', repr(data)  
  19.   
  20. time.sleep(60)  
  21. s.close()  


运行后,可以看到,服务器端,会打出:

Hello,

word!

原文地址:https://www.cnblogs.com/DjangoBlog/p/4275466.html