Skip to content

Instantly share code, notes, and snippets.

@mpj
Created May 3, 2015 08:12
Show Gist options
  • Save mpj/a979ded460dd52eb536a to your computer and use it in GitHub Desktop.
Save mpj/a979ded460dd52eb536a to your computer and use it in GitHub Desktop.
Java/Node socket client interaction
var net = require('net');
var client = net.connect(4444, 'localhost');
client.setEncoding('utf8');
setInterval(function() {
console.log("Writing....")
var ret = client.write('Hello from node.js\n');
console.log("Wrote", ret)
}, 1000);
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static final int port = 12345;
private ServerSocket server;
public void listen() {
try {
server = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port 4444");
System.exit(-1);
}
while(true){
try {
System.out.println("Waiting for connection");
final Socket socket = server.accept();
final InputStream inputStream = socket.getInputStream();
final InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(streamReader);
// readLine blocks until line arrives or socket closes, upon which it returns null
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
/* creating new server and call it's listen method */
public static void main(String[] args) {
new SocketServer().listen();
}
}
@chavan-gopal
Copy link

Hi @mpj, can you also share a sample where you send data from java and read it in node?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment