【问题标题】:Python socket server errorPython套接字服务器错误
【发布时间】:2014-03-09 23:32:03
【问题描述】:

在将数据发送到服务器时出现一些错误。我对 Python 套接字非常陌生,这是一个简单的脚本。在这里

Exception happened during processing of request from ('ip', 53863)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 284, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 310, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 323, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.7/SocketServer.py", line 638, in __init__
    self.handle()
  File "serv.pyz", line 9, in handle
    print(self.client_address + ' : ' + self.data)
TypeError: can only concatenate tuple (not "str") to tuple

Serv.pyz(我知道,应该是.py)

import SocketServer


class SEER(SocketServer.BaseRequestHandler):

def handle(self):
    while 1:
        self.data = self.request.recv(9000)
        print(self.client_address + ' : ' + self.data)
server = SocketServer.TCPServer(('', 4857), SEER)
server.serve_forever()

另外,我如何添加一个 Client 类来存储诸如 Client.room_id 或 Client.joinRoom(1) 之类的东西?

【问题讨论】:

    标签: python sockets tcp python-2.7


    【解决方案1】:

    self.client_address 是元组,你应该使用self.client_address[0] 而不是this。

    【讨论】:

      【解决方案2】:

      尝试将打印功能更改为:

          print(str(self.client_address) + ' : ' + str(self.data))
      

      根据错误,其中一个变量是元组,因此应该将其转换为字符串。

      【讨论】:

        【解决方案3】:

        问题是由回溯给出的:

        print(self.client_address + ' : ' + self.data)
        

        self.client_address 是一个元组。你想要(在这种情况下) self.client_address[0] 要么,要么在单独的行上打印出来

        【讨论】:

          【解决方案4】:

          self.client_address 是一个元组,而不是一个字符串!所以你需要打印它的 str() 。

          SEER是你的客户端类,所以创建self.room_id等来存储客户端状态和实现方法。

          TCP 也是一种流协议,因此您需要在其之上实现消息协议以确保您拥有完整的消息。示例见this answer。

          【讨论】:

            猜你喜欢
            • 2018-04-24
            • 2011-04-21
            • 1970-01-01
            • 2014-04-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多