Skip to content Skip to sidebar Skip to footer

Python Socket: Can Only Concatenate Str Not Bytes To Str. How To Encode So It Won't Give Me This Error?

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 Mak

Solution 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")

whileTrue:
    try:
        command = input(client_ip + "> ")
        iflen(command.split()) != 0:
            client_socket.send(bytes(command, 'utf-8'))
        else:
            continueexcept EOFError:
        print("ERROR INPUT NOT FOUND. Please type 'help' to get a list of commands.\n")
        continueif 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")

whileTrue:
    print('\nWaiting for a command....')        
    command = connection_socket.recv(1024).decode()

    split_command = command.split()
    print("Received command : ", command)
    if command == "quit":
        breakif command[:2] == "cd":
        iflen(command.split()) == 1:
            connection_socket.send(bytes(os.getcwd(), 'utf-8'))
        eliflen(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!

Solution 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")

Solution 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

Post a Comment for "Python Socket: Can Only Concatenate Str Not Bytes To Str. How To Encode So It Won't Give Me This Error?"