【问题标题】:having this error TypeError: cannot concatenate 'str' and 'int' objects when trying to do math with variables stored with pickle出现此错误 TypeError: cannot concatenate 'str' and 'int' objects when trying to do math variables with stored with pickle
【发布时间】:2016-06-13 17:49:01
【问题描述】:

我遇到了这个错误

TypeError: cannot concatenate 'str' and 'int' objects

当我尝试使用 pickle 从客户端文件发送到服务器的变量进行计算时,当第二台计算机加入我的服务器时,这是我的服务器代码

import socket, select, pickle
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('', 4000))
server.listen(5)
pjoin = 0

clients = []
while True:
    Connections, wlist, xlist = select.select([server], [], [], 0.05)

    for Connection in Connections:
        client, Informations = Connection.accept()
        clients.append(client)

        clientsList = []
    try:
        clientsList, wlist, xlist = select.select(clients, [], [], 0.05)
    except select.error:
        pass
    else:
        for clientInList in clientsList:
            join = clientInList.recv(1024)
            join = pickle.loads(join)
            print(join)
            pjoin += (join)
            pjoin = pickle.dumps(pjoin)
            clientInList.send(pjoin)

clientInList.close()
server.close()

我有它,所以当客户端加入时,它会将具有值的变量 join 发送到服务器,然后服务器将其添加到 pjoin 并将其发回。这样,当使用相同客户端文件的第二台计算机加入同一台服务器时,它最终会向第二台计算机发送 2,这样客户端文件就可以知道它是第一个加入服务器还是第二个,依此类推。

但这对我不起作用,服务器一直给我上面的错误。

【问题讨论】:

  • 我们不需要所有这些代码。只是它在一点上下文中发生的行和完整的堆栈跟踪会很好。实际上,错误告诉您究竟出了什么问题:您正在尝试添加一个字符串 (str) 和一个数字 (int)。如果没有一种或另一种方式的显式转换,Python 不会这样做。

标签: python python-2.7 integer pickle


【解决方案1】:

您将pjoin 整数 替换为字符串:

# at the top
pjoin = 0

# inside the while True and for clientInList loops
pjoin = pickle.dumps(pjoin)

pickle.dumps() 返回一个字符串对象。下次您收到来自客户端的响应时,您现在将把一个整数加到一个字符串中:

pjoin += (join)

在我看来,您可以通过不将 pjoin 重新用于 pickle.dumps() 结果来解决此问题:

for clientInList in clientsList:
    join = clientInList.recv(1024)
    join = pickle.loads(join)
    print(join)
    pjoin += (join)
    response = pickle.dumps(pjoin)
    clientInList.send(response)

【讨论】:

    猜你喜欢
    • 2019-07-12
    • 1970-01-01
    • 2020-11-21
    • 2018-06-26
    • 1970-01-01
    • 2022-11-01
    • 2021-09-08
    • 1970-01-01
    • 2021-02-02
    相关资源
    最近更新 更多