def spawn_read(): message = self.stream.read_with_checker(Box().check) #print "message, len: %s, content: %r" % (len(message), message) if message: req_box = Box() req_box.unpack(message) print req_box req_box.body = 'ok' buf = req_box.pack() self.stream.write(buf[:2]) self.stream.write(buf[2:]) if self.stream.closed(): print 'client closed' # 说明客户端断掉链接了 return
#!/usr/bin/env python # -*- coding: utf-8 -*- import time from websocket import create_connection from websocket import ABNF from reimp import Box ws = create_connection("ws://127.0.0.1:8000/echo") # ws = create_connection("ws://115.28.224.64:8000/echo") box = Box() box.cmd = 101 box.body = '我爱你' t1 = time.time() # 二进制协议 ws.send(box.pack(), ABNF.OPCODE_BINARY) result = ws.recv() print 'time past: ', time.time() - t1 print "Received '%r'" % result recv_box = Box() recv_box.unpack(result) print recv_box ws.close()
# -*- coding: utf-8 -*- from netkit.contrib.tcp_client import TcpClient from reimp import logger, Box tcp_client = TcpClient(Box, address=('127.0.0.1', 7777)) # tcp_client = TcpClient(Box, '127.0.0.1', 7777) tcp_client.connect() box = Box() box.body = '我爱你' tcp_client.write(box) while 1: # 阻塞 box = tcp_client.read() print box if not box: print 'server closed' break tcp_client.close()