I am trying to connect to localhost with a java app, and I have a server side code with nodeJS and.It's my first time to deal with nodeJS, when I created a server.js and client.js every thing was working correctly and I could send and receive messages to and from the server but when I tried to use java code(Socket) nothing happened but there is no errors. I can't find the reason and it's my first time I use nodeJS so I feel stuck, can any one give me advises or find out where is my mistake.
Here is my java code
String hostName = "localhost";
int portNumber = 8081;
try {
System.out.println("Connecting to " + hostName + " on port " + portNumber);
Socket client = new Socket(hostName, portNumber);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
out.writeInt(5);
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e) {
e.printStackTrace();
}
And here is my server code with nodeJS
var http = require('http');
var fs = require('fs');
var url = require('url');
// Create a server
http.createServer( function (request, response) {
var b = new Buffer("Return something");
response.write(b.toString());
console.log('listening to client');
response.end();
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
And here is my client code with nodeJS, it works fine
var http = require('http');
// Options to be used by request
var options = {
host: 'localhost',
port: '8081',
path: '/index.htm'
};
// Callback function is used to deal with response
var callback = function(response){
// Continuously update stream with data
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
// Data received completely.
console.log(body);
});
}
// Make a request to the server
var req = http.request(options, callback);
req.end();