Kilon
Kilon

Reputation: 2002

socket sendall() does not send the data

I have this code. Its not the entire code because its a Blender addon with many lines that are unrelated to sockets so I give here only the part that deals with the sockets which I kept isolated from the rest of the program.

If you want to see the entire code, it can be found here

http://pastebin.com/iqN7tr8E

def create_thread():

    global threadSocket,listening
    threadSocket = threading.Thread(name='threadSocket', target= socket_listen)
    listening = True
    create_socket_connection()
    threadSocket.start()


def socket_listen():
    global receivedSocket,listening, receivedData,socketServer, socketMessages, pherror
    socketServer.listen(5)

    while listening:
        (receivedSocket , adreess) = socketServer.accept()
        receivedData = (receivedSocket.recv(1024)).decode("utf-8")[:-2]

        socketMessages.append(receivedData)
        receivedSocket.sendall('Hello from Blender!\n')
        receivedSocket.close()




def create_socket_connection():
    global socketServer
    socketServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socketServer.bind(('127.0.0.1',4000))

I am using telnet to test the socket with telnet 127.0.0.1 4000, telnet can send the data but never receives any. As you can see my socket is blocking inside its own thread so it does not block the entire programs execution. I assume that sendall tries to send everything and for some reason it cannot connect back to telnet for sending . Am I doing something wrong here ?

Upvotes: 1

Views: 4431

Answers (1)

falsetru
falsetru

Reputation: 369154

Following line will raises error, because there's no socketMessages defined according to the given code.

socketMessages.append(receivedData)

exception in above line will prevent the excution of next line (sendall).

To solve the problem, define the socketMessages as a list or remove the above line.


UPDATE after seeing OP's comment:

socket.sendall accepts byte string (str in Python 2.x, bytes in Python 3.x). In Python 3.x, you should use bytes literal as follow.

receivedSocket.sendall(b'Hello from Blender!\n')

Upvotes: 1

Related Questions