【问题标题】:Python Socket: Can only concatenate str not bytes to str. How to encode so it won't give me this error?Python Socket:只能将 str 而不是字节连接到 str。如何编码,这样它就不会给我这个错误?
【发布时间】:2021-01-15 18:32:17
【问题描述】:

这是我的完整代码:它使用主机端口的用户输入。

服务器端代码:

import socket
import subprocess, os

print("#####################")
print("# Python Port Maker #")
print("#                   #")
print("#'To Go Boldy Where'#")
print("#  No Other Python  #")
print("#      Has Gone     #")
print("#      By Riley     #")
print("#####################")

print(' [*] Be Sure To use https://github.com/Thman558/Just-A-Test/blob/master/socket%20client.py 
on the other machine')

host = input(" [*] What host would you like to use? ")
port = int(input(" [*] What port would you like to use? "))
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 
server_socket.bind((host, port))

server_socket.listen(5)  
print("\n[*] Listening on port " +str(port)+ ", waiting for connections.")

client_socket, (client_ip, client_port) = server_socket.accept()
print("[*] Client " +client_ip+ " connected.\n")

while True:
try:
    command = input(client_ip+ "> ")
    if(len(command.split()) != 0):
        client_socket.send(b'command')
    else:
        continue
except(EOFError):
        print("ERROR INPUT NOT FOUND. Please type 'help' to get a list of commands.\n")
        continue

if(command == "quit"):
    break

data = client_socket.recv(1024)
print(data + "\n")

client_socket.close()

又报错了:

print(:"Recieved Command : ' +command)
TypeError: can't concat str to bytes

当用户仅在给定命令时才连接时它工作正常,当此错误发生时不确定它是否可能是 data 变量,但此代码只是不想工作大声笑。这是我用来连接客户端的代码:

import socket
import subprocess, os

print("######################")
print("#                    #")
print("#     The Socket     #")
print("#     Connecter      #")
print("#                    #")
print("#     By Yo Boi      #")
print("#       Riley        #")
print("######################")

host = input("What host would you like to connect to? ")
port = int(input("What port is the server using? "))
connection_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
connection_socket.connect((host, port))
print("\n[*] Connected to " +host+ " on port " +str(port)+ ".\n")

while True:

command = connection_socket.recv(1024)
split_command = command.split()
print("Received command : " +command)
if command == "quit":
    break

if(command.split()[0] == "cd"):
        if len(command.split()) == 1:
            connection_socket.send((os.getcwd()))
        elif len(command.split()) == 2:
            try:
                os.chdir(command.split()[1])
                connection_socket.send(("Changed directory to " +     os.getcwd()))
            except(WindowsError):
                connection_socket.send(str.encode("No such directory     : " +os.getcwd()))

else:
    proc = subprocess.Popen(command, shell=True,        stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    stdout_value = proc.stdout.read() + proc.stderr.read()
    print(stdout_value + "\n")
    if(stdout_value != ""):
        connection_socket.send(stdout_value)
    else:
        connection_socket.send(command+ " does not return anything")


connection_socket.close()

【问题讨论】:

    标签: python sockets networking


    【解决方案1】:

    如果你打印type(data),你会注意到它不是一个字符串而是一个字节实例。 要连接换行符,您可以这样写:

    print(data + b"\n")
    

    【讨论】:

    • 在用户机器上它说这个 print("Received command : " +command) TypeError: can only concatenate str (not "bytes") to str 我还发布了我用来连接的脚本用户到主机我可以在主机端连接,但是当我尝试说查看目录时,它只是说 b"\n"
    • 无论您在哪里遇到此错误,只需将 "..." 替换为 b"..."
    • 它只打印数据末尾的任何内容+如果我输入 print(data + b"\n") 它会打印 b"\n"
    • 这意味着你的数据是空的
    • 是的,它是字符串格式,所以我必须将所有 str 编码为字节
    【解决方案2】:

    socket.recv(size) 返回一个字节对象,您尝试将其附加到字符串中,这会导致错误。 您可以通过在附加换行符之前执行 str(data , 'utf-8') 将套接字消息转换为字符串

    print() 方法无论如何都会添加一个换行符,因此您可以只写 print(data) 就可以了

    【讨论】:

    • 它没有给我一个错误但是当我尝试进入一个目录时它只是说 b' ' 然后在用户机器上它说 "print("Received command : " +command) TypeError:只能将 str(不是“字节”)连接到 str
    • 您必须将command 转换为字符串或“收到的命令:”转换为字节才能正常工作
    • 是的,我明白了,我必须将所有 str 行编码为字节,这很有效。谢谢!
    【解决方案3】:

    所以,除了数据类型不匹配之外,您的脚本还有很多错误。我会告诉你strbyte 不匹配有什么问题。每当您将字符串转换为字节时,您都必须指定编码方法。不管怎样,我已经修复了你的脚本,剩下的事情就交给你了。 ;)

    服务器脚本

    import socket
    
    print("#####################")
    print("# Python Port Maker #")
    print("#                   #")
    print("#'To Go Boldy Where'#")
    print("#  No Other Python  #")
    print("#      Has Gone     #")
    print("#      By Riley     #")
    print("#####################")
    
    print(' [*] Be Sure To use https://github.com/Thman558/Just-A-Test/blob/master/socket%20client.py on the other machine')
    
    host = input(" [*] What host would you like to use? ")
    port = int(input(" [*] What port would you like to use? "))
    
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind((host, port))
    
    server_socket.listen(5)
    
    print("\n[*] Listening on port " + str(port) + ", waiting for connections.")
    
    client_socket, (client_ip, client_port) = server_socket.accept()
    print("[*] Client " + client_ip + " connected.\n")
    
    while True:
        try:
            command = input(client_ip + "> ")
            if len(command.split()) != 0:
                client_socket.send(bytes(command, 'utf-8'))
            else:
                continue
        except EOFError:
            print("ERROR INPUT NOT FOUND. Please type 'help' to get a list of commands.\n")
            continue
    
        if command == "quit":
            break
    
        data = client_socket.recv(1024).decode()
        print(data + "\n")
    
    client_socket.close()
    

    客户端脚本

    import os
    import socket
    import subprocess
    
    print("######################")
    print("#                    #")
    print("#     The Socket     #")
    print("#     Connecter      #")
    print("#                    #")
    print("#     By Yo Boi      #")
    print("#       Riley        #")
    print("######################")
    
    host = input("What host would you like to connect to? ")
    port = int(input("What port is the server using? "))
    
    connection_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    connection_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    connection_socket.connect((host, port))
    print("\n[*] Connected to " + host + " on port " + str(port) + ".\n")
    
    while True:
        print('\nWaiting for a command....')        
        command = connection_socket.recv(1024).decode()
    
        split_command = command.split()
        print("Received command : ", command)
        if command == "quit":
            break
    
        if command[:2] == "cd":
            if len(command.split()) == 1:
                connection_socket.send(bytes(os.getcwd(), 'utf-8'))
            elif len(command.split()) == 2:
                try:
                    os.chdir(command.split()[1])
                    connection_socket.send(bytes("Changed directory to " + os.getcwd(), 'utf-8'))
                except WindowsError:
                    connection_socket.send(str.encode("No such directory     : " + os.getcwd()))
    
        else:
            proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                    stdin=subprocess.PIPE)
            stdout_value = proc.stdout.read() + proc.stderr.read()
            print(str(stdout_value) + "\n")
            if stdout_value != "":
                connection_socket.send(stdout_value)
            else:
                connection_socket.send(bytes(str(command) + ' does not return anything', 'utf-8'))
    
    connection_socket.close()
    

    提示:大多数错误都包括逻辑缺陷!

    【讨论】:

      猜你喜欢
      • 2021-03-11
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多