Python错误:printdata +“ \ n”TypeError:尝试通过网络套接字发送命令时,无法将str连接为字节

问题描述

您好,我正在尝试通过python套接字将命令从一台计算机发送到另一台计算机。我能够成功连接到计算机并看到用户的IP地址,但是当我尝试从主机发送命令时,它给了我这个错误client_socket.send(command) TypeError:需要一个类似字节的对象,而不是'str'

这是我所有的代码:

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("#####################")

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(data + "\n")
TypeError: can't concat str to bytes

有帮助吗?谢谢

解决方法

不确定是否可以,但是您可以尝试以下方法:

<h2>Index</h2>
<div id="num-unresolved-tickets" class="panel-body">
    <h2 class="text-center">
        <b style="color:red"> @ViewBag.Message</b>
    </h2>
</div>

这样,您的命令将以字节而不是字符串发送。

,

client_socketsocket object,并以bytes作为参数。

由于command是字符串,请尝试client_socket.send(b'command')将其用作字节对象。

编辑

client_socket.recv(1024)返回bytes对象,因此data变量是字节对象。

尝试print(data)或转换字节对象字符串print(data.decode('utf-8') + '\n')

此处使用utf-8是因为它是一种非常常见的编码,但是您需要使用数据实际所在的编码。

如果它不起作用,请尝试使用此answer

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...