Python/2.7 information
python websocket 기초 참고용.(그냥 소켓 아님.)
qkqhxla1
2015. 4. 26. 15:20
나중에 쓸것같아서 기본적인것만 적어둠.
웹소켓 가장 기본적인 통신 예제이며, 윈도우에서 작동을 확인했다. 이거 파이썬 예시를 한동안 못찾다가
스택오버플로우에서 기초적이고 좋은 예시를 발견해서 가져다가 씀.
웹소켓 공식 문서 : http://dev.w3.org/html5/websockets/
웹소켓 테스트용 사이트 : https://www.websocket.org/echo.html
tornado : https://pypi.python.org/pypi/tornado
서버 실행시키고 클라이언트 실행시키면 예시 메시지까지 같이 보인다. 별 설명 필요없음.
서버.
# -*- encoding: cp949 -*- import datetime import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web class WSHandler(tornado.websocket.WebSocketHandler): clients = [] def open(self): print 'new connection' self.write_message("Hello World") WSHandler.clients.append(self) def on_message(self, message): print 'message received %s' % message self.write_message('ECHO: ' + message) def on_close(self): print 'connection closed' WSHandler.clients.remove(self) @classmethod def write_to_clients(cls): print "Writing to clients" for client in cls.clients: client.write_message("Hi there!") application = tornado.web.Application([ (r'/ws', WSHandler), ]) if __name__ == "__main__": http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) tornado.ioloop.IOLoop.instance().add_timeout(datetime.timedelta(seconds=15), WSHandler.write_to_clients) tornado.ioloop.IOLoop.instance().start()
클라이언트.
#-*- coding: cp949 -*- import tornado.websocket from tornado import gen @gen.coroutine def test_ws(): client = yield tornado.websocket.websocket_connect("ws://localhost:8888/ws") client.write_message("Testing from client") msg = yield client.read_message() print("msg is %s" % msg) msg = yield client.read_message() print("msg is %s" % msg) msg = yield client.read_message() print("msg is %s" % msg) client.close() if __name__ == "__main__": tornado.ioloop.IOLoop.instance().run_sync(test_ws)