Created
May 3, 2015 08:12
-
-
Save mpj/a979ded460dd52eb536a to your computer and use it in GitHub Desktop.
Java/Node socket client interaction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @mpj, can you also share a sample where you send data from java and read it in node?