javatypescriptsockets

Send message from Java to socket server written in TypeScript


Server myserver.ts written in TypeScript:

import { createServer } from 'net';

function main() {
   const socketServer = createServer((socket) => {

       socket.on('data', function (data) {
           console.log('Received: ' + data.toString());
       })

       socket.pipe(socket);
   });

   socketServer.listen(60001, '127.0.0.1');
}

main();

Client written in Java:

 public static void main(String[] args) throws Exception {

    try (var socket = new Socket("127.0.0.1", 60001);
         var outStream = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
        outStream.write("Hey there");
        outStream.flush();
    }
  }

Run server in console: ts-node ./myserver.ts. And then run java program. Output in server's console:

$ ts-node ./myserver.ts
Received: Hey there
Error: read ECONNRESET
    at TCP.onStreamRead (node:internal/stream_base_commons:218:20) {
  errno: -4077,
  code: 'ECONNRESET',
  syscall: 'read'
}

As you can see I received 'Hey there'. But why server shuts down? I understand that client closed the connection but anyway server should continue listening, right?

My goal is to send multiple separate messages to the .ts server. And I expect server to be alive all the time.


Solution

  • I commented out socket.pipe(socket); line in .ts script and it works now.