【问题标题】:Python: WinError 10045: The attempted operation is not supported for the type of object referencedPython:WinError 10045:引用的对象类型不支持尝试的操作
【发布时间】:2019-02-17 21:53:50
【问题描述】:

我正在使用客户端/服务器程序创建一个凯撒密码程序。客户端将输入消息和密钥,服务器将返回密文。这是我的服务器代码:

import socket

def getCaesar(message, key):
    cipher = "" 

    for i in message: 
        char = message[i] 

        # Encrypt uppercase characters 
        if (char.isupper()): 
            cipher += chr((ord(char) + key-65) % 26 + 65) 

        # Encrypt lowercase characters 
        else: 
            cipher += chr((ord(char) + key - 97) % 26 + 97) 

    return cipher 

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=socket.gethostname()
port=4000

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

s.bind((host,port))
s.listen(5)
print("Listenting for requests")

while True:
    s,addr=s.accept()
    print("Got connection from ",addr)
    print("Receiving...")

    message,key=s.recv(1024)
    resp=getCaesar(message, key)

    s.send(resp)
s.close()

错误消息调用此行:s.send(message, key) 并出现此错误:

OSError: [WinError 10045] 引用的对象类型不支持尝试的操作。这个错误是什么意思?

我的客户代码:

import socket

def getMessage():
    print('Enter your message:')
    return input()

def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (26))
        key = int(input())
        if (key >= 1 and key <= 26):
            return key

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=socket.gethostname()
port=4000
s.connect((host,port))


message = getMessage()
key = getKey()

message=message.encode()


s.send(message, key)
cipher= s.recv(1024)

print('Ciphertext: ')
print(cipher)
s.close()

【问题讨论】:

    标签: python client-server


    【解决方案1】:

    查看帮助(socket.send):

    Help on built-in function send:
    
    send(...) method of socket.socket instance
        send(data[, flags]) -> count
    
        Send a data string to the socket.  For the optional flags
        argument, see the Unix manual.  Return the number of bytes
        sent; this may be less than len(data) if the network is busy.
    

    因此,s.send(message, key) 行可能与您预期的方式不同:它仅发送 message 和 key 被解释为标志,而不是 message 和 key。尝试分别发送message 和key。并且不要忘记分别recv他们。

    【讨论】:

      猜你喜欢
      • 2012-05-24
      • 1970-01-01
      • 2014-12-18
      • 2020-11-28
      • 2021-08-17
      • 2017-07-15
      • 2020-02-29
      相关资源
      最近更新 更多