2016-11-14 4 views
0

파이썬 websocket 클라이언트 용 샘플 코드를 here에서 얻었습니다. 아래 문제점이 있습니다. 이 코드를 내가 문제로 점점 이후 장소의 몇 원래에서 조금 편집 :Python websocket 객체에 'write_message'오류가 없습니다.

  • connect 메소드를 제거하고 생성자를 합병했다. 나는 을 받고 'self._ws_connection'문제를 찾을 수 없습니다.

  • WebSocketClient __init __() 메서드를 'url'을 허용하도록 변경했으며 인수를 삭제하고 ''인수를 제거했습니다. ''의 의미가 무엇인지 모르겠습니다. 을 의미합니다.

Problem1 :

Traceback (most recent call last): 
    File "websocketcli.py", line 138, in <module> 
    main() 
    File "websocketcli.py", line 129, in main 
    client.send('Hello world!') 
    File "websocketcli.py", line 49, in send 
    self._ws_connection.write_message(escape.utf8(json.dumps(data))) 
    File "https://stackoverflow.com/users/anjangam/pyvenv/venv/lib/python2.7/site-packages/tornado/websocket.py", line 970, in write_message 
    return self.protocol.write_message(message, binary) 
AttributeError: 'NoneType' object has no attribute 'write_message' 

문제 2 : 내가 제거하면 '*'는 WbSocketClient 생성자에서, 나는 다음과 같은 오류가 발생, 문제는 1 주에서 발견 된 것과 거의 동일 : 파이썬 2.7.8 버전을 사용하고 있습니다.

Traceback (most recent call last): 
    File "websocketcli.py", line 138, in <module> 
    main() 
    File "websocketcli.py", line 129, in main 
    client.send('Hello world!') 
    File "websocketcli.py", line 52, in send 
    self._ws_connection.write_message(escape.utf8(json.dumps(data))) 
    File "https://stackoverflow.com/users/anjangam/pyvenv/venv/lib/python2.7/site-packages/tornado/websocket.py", line 970, in write_message 
    return self.protocol.write_message(message, binary) 
AttributeError: 'NoneType' object has no attribute 'write_message' 

클라이언트 코드 :

from tornado import escape 
from tornado import gen 
from tornado import httpclient 
from tornado import httputil 
from tornado import ioloop 
from tornado import websocket 

import functools 
import json 
import time 


APPLICATION_JSON = 'application/json' 

DEFAULT_CONNECT_TIMEOUT = 60 
DEFAULT_REQUEST_TIMEOUT = 60 


class WebSocketClient(): 
"""Base for web socket clients. 
""" 
def __init__(self, connect_timeout=DEFAULT_CONNECT_TIMEOUT, 
      request_timeout=DEFAULT_REQUEST_TIMEOUT): 

    self.connect_timeout = connect_timeout 
    self.request_timeout = request_timeout 

def connect(self, url): 
    """Connect to the server. 
    :param str url: server URL. 
    """ 
    headers = httputil.HTTPHeaders({'Content-Type': APPLICATION_JSON}) 
    request = httpclient.HTTPRequest(url=url, 
            connect_timeout=self.connect_timeout, 
            request_timeout=self.request_timeout, 
            headers=headers) 
    self._ws_connection = websocket.WebSocketClientConnection(ioloop.IOLoop.current(), 
                request) 
    self._ws_connection.connect_future.add_done_callback(self._connect_callback) 
    print 'Connection: ', self._ws_connection 

    def send(self, data): 
     """Send message to the server 
     :param str data: message. 
     """ 
     if not self._ws_connection: 
      raise RuntimeError('Web socket connection is closed.') 

     self._ws_connection.write_message(escape.utf8(json.dumps(data))) 

    def close(self): 
     """Close connection. 
     """ 

     if not self._ws_connection: 
      raise RuntimeError('Web socket connection is already closed.') 

     self._ws_connection.close() 

    def _connect_callback(self, future): 
     if future.exception() is None: 
      self._ws_connection = future.result() 
      self._on_connection_success() 
      self._read_messages() 
     else: 
      self._on_connection_error(future.exception()) 

    @gen.coroutine 
    def _read_messages(self): 
     while True: 
      msg = yield self._ws_connection.read_message() 
      if msg is None: 
       self._on_connection_close() 
       break 

      self._on_message(msg) 

    def _on_message(self, msg): 
     """This is called when new message is available from the server. 
     :param str msg: server message. 
     """ 

     pass 

    def _on_connection_success(self): 
     """This is called on successful connection ot the server. 
     """ 

     pass 

    def _on_connection_close(self): 
     """This is called when server closed the connection. 
     """ 
     pass 

    def _on_connection_error(self, exception): 
     """This is called in case if connection to the server could 
     not established. 
     """ 

     pass 


class TestWebSocketClient(WebSocketClient): 

    def __init__(self, url): 
     WebSocketClient.__init__(self, url) 

    def _on_message(self, msg): 
     print(msg) 
     deadline = time.time() + 1 
     ioloop.IOLoop().instance().add_timeout(
      deadline, functools.partial(self.send, str(int(time.time())))) 

    def _on_connection_success(self): 
     print('Connected!') 
     self.send(str(int(time.time()))) 

    def _on_connection_close(self): 
     print('Connection closed!') 

    def _on_connection_error(self, exception): 
     print('Connection error: %s', exception) 


def main(): 
    client = TestWebSocketClient() 
    client.connect('ws://localhost:8888/ws') 
    client.send('Hello world!') 


    try: 
     ioloop.IOLoop.instance().start() 
    except KeyboardInterrupt: 
     client.close() 


if __name__ == '__main__': 
    main() 

답변

1

당신이 파이썬 3.5에 작품을 잘 참조 원래 코드는,하지만 난 당신이 파이썬 2가에 의한 것 휴식 것이 그 이유의 일부 버전을 사용하는 의심 당신이 언급 한 별표는 파이썬 2의 기능이 아닙니다. PEP 3102은 이것에 관해 이야기합니다. 그러나 간단히 말해서 별표는 매개 변수가 제공된 순서에 의존하지 않고 함수 호출이 키워드 인수를 전달하도록 강제 할 것입니다.

예를 들어 다음과 같은 기능 :

# we can use positional arguments on this one 
def test(a, b): 
    print(a, b) 

# this will require keyword arguments to be supplied on function calls 
def test_keywords_args_required(*, a, b): 
    print(a, b) 

test(1, 2) # test can be called using positional arguments 
test_keywords_args_required(1, 2) # this will error out. Needs keywords args! 
test_keywords_args_required(a=1, b=2) # this will work! 

원래 링크에서 제공되는 코드를 사용하고 별표를 제거하면이 코드가 작동 (파이썬 2.7으로 확인)해야한다.

관련 문제