Python Socket: Can only concatenate str not bytes to str. How to encode so it won't give me this error?

烈酒焚心 提交于 2021-02-17 05:54:06

问题


Here is my entire code: It uses user input for the host and the port.

Server side code:

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

The error again:

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

It works fine when a user connects only when given commands is when this error happens not sure if it might be the data variable but this code just don't wanna work Lol. This is the code I am using to connect the client:

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

回答1:


So, your script had many mistakes apart from the data type mismatch. I will tell you what was wrong with the str and byte mismatch. Whenever you convert a string to byte you must specify the encoding method. Anyway, I have fixed your script and I leave it to you to figure out the remaining things. ;)

Server script

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

Client script

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

Tip: Most of the mistakes included logical flaws!




回答2:


If you print type(data) you will notice it is not a string but a bytes instance. To concatenate a newline you could write this:

print(data + b"\n")



回答3:


socket.recv(size) returns a bytes object which you're trying to append to a string and that's causing the error. You could convert the socket message to a string by doing str(data , 'utf-8') before appending the newline

The print() method adds a newline anyway so you could just write print(data) and that would work



来源:https://stackoverflow.com/questions/64131594/python-socket-can-only-concatenate-str-not-bytes-to-str-how-to-encode-so-it-wo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!