WhiplashOne
WhiplashOne

Reputation: 321

Node.js - Write after end error

I have setup a TCP server using Node.js which is running on my Raspberry pi 3. I communicate with the server using an android client (Code from [this][1] tutorial). I get a response from the server only when the client connects to connects to it for the first time.

When I try to make another request to it, the request is received and processed but while sending the response I get an error saying: write after end.

Code(Edited):

var net = require('net');
var devList = [];
var dev_msg; 

function serverCallback(socket){
    console.log("-----------------------------------------------------");

    socket.setNoDelay(true);

    socket.on('data', function(data){
        var req = data.toString();

        console.log(req);

        InitSystems(socket);
    });

    socket.on('error', function(err){
        console.log(""+err);
    });

    socket.on('end', function(){
        console.log("Write end");
    });
}


function InitSystems(socket){
  socket.write("Message 1: Hi!");
  socket.end();

  //After 2nd request from client
  socket.write("Message 2: Event has successfully taken place!"); //<-- Error here
  socket.end(); 
}

console.log("Server now running!");

var netServer = net.createServer(serverCallback);
netServer.listen(6969);

EDIT: Android code:

try{
            socket = new Socket("192.168.1.13", 6969);

            socket.setSoTimeout(24 * 60 * 60 * 1000);
            socket.setKeepAlive(true);

            dOut = new DataOutputStream(socket.getOutputStream());

            dOut.writeUTF("INIT");
            dOut.flush();

            ba = new ByteArrayOutputStream(1024);
            buffer = new byte[1024];

            int bytesRead;
            is = socket.getInputStream();

            while((bytesRead = is.read(buffer)) != -1){
                ba.write(buffer, 0, bytesRead);
                res += ba.toString("UTF-8");
            }

            Log.d(TAG, res);

            connStat = true;
        }catch (UnknownHostException e) {
            Log.d(TAG, e.toString());
        } catch(SocketException e){
            Log.d(TAG, e.toString());
        } catch (IOException e){
            try{
                Thread.sleep(2100);
            }catch (Exception e1){

            }finally {
                connStat = false;
            }
        } catch (Exception e) {
            Log.d(TAG, e.toString());
        }

Thanks in advance!

Upvotes: 1

Views: 1338

Answers (1)

Ryan Wheale
Ryan Wheale

Reputation: 28410

Here is your problem (just as you commented):

function InitSystems(socket){
  socket.write("Message 1: Hi!");
  socket.end();

  //After 2nd request from client
  socket.write("Message 2: Event has successfully taken place!"); //<-- Error here
  socket.end(); 
}

You are doing a write() after an end() is called, which you are not allowed to do. You can think of a socket as a wire connected between you (the server) and a client. As long as the socket is open you can send messages back and forth across the wire. Once you call end(), there wire is cut (socket is closed) and you can no longer send messages. Any attempt to do so will result in the error you are receiving.

Also noteworthy, JavaScript keeps executing after you call socket.end(), so your code above attempts to write -> end -> write -> end every time the function is called. I'm not really sure what you are trying to acheive, but you shouldn't need to call socket.end() until you are completely done with the socket and no longer want to send any more messages.

If you want to conditionally write messages, you will need to keep some sort of state like this:

var reqCount = 0;
function InitSystems(socket){
    switch (reqCount) {
        case 0:
            socket.write("Message 1: Hi!");
            break;
        case 1:
            socket.write("Message 2: Event has successfully taken place!");
            break;
    }

    // You may want to do something to signify the end of a message
    socket.write('END OF MESSAGE');
    reqCount++;
}

Upvotes: 1

Related Questions