-1

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();
Khalid Ali
  • 373
  • 1
  • 15
  • oh, it looks like your listening with a node HTTP server but you arn't sending a valid HTTP request to the server, just a string an integer – slipperyseal Oct 23 '17 at 04:32
  • It doesn't work, when I execute from java app my server doesn't take any action but when I use client.js the listener works correctly. – Khalid Ali Oct 23 '17 at 04:34
  • How can I check this ? – Khalid Ali Oct 23 '17 at 04:35
  • 2
    Possible duplicate of [Java: Simple http GET request using TCP sockets](https://stackoverflow.com/questions/33015868/java-simple-http-get-request-using-tcp-sockets) – Catchwa Oct 23 '17 at 04:35
  • Could you tell me where can I find the solution in this post you refer to ??? – Khalid Ali Oct 23 '17 at 04:48

2 Answers2

2

Try this ...

String hostName = "127.0.0.1";
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);
    PrintWriter pw = new PrintWriter(client.getOutputStream());
    pw.println("GET / HTTP/1.1");
    pw.println("Host: 127.0.0.1");
    pw.println()
    pw.println("<html><body><h1>Hello world<\\h1><\\body><\\html>")
    pw.println()
    pw.flush();
    BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
    String t;
    while((t = br.readLine()) != null) System.out.println(t);
    br.close();

}catch(IOException e) {
   e.printStackTrace();
}
indranil32
  • 140
  • 1
  • 9
  • Could you tell me what was my mistake exactly, I have no time to discover it , I'm done :D lol – Khalid Ali Oct 23 '17 at 05:08
  • yeah. you can check the /etc/hosts to see if there are mapping from localhost to 127.0.0.1. i do not think each tool/lang would do the map automatically localhost – machinarium Oct 23 '17 at 05:08
  • @KhalidAli your server is listening to HTTP request and you were sending TCP data to it. I just added the HTTP headers/format and the line break (pw.println()), which is very important – indranil32 Oct 23 '17 at 05:12
  • So do you know how I make my server listen to TCP data directly ? just for learning another method. @indrainl32 – Khalid Ali Oct 23 '17 at 05:16
  • Check this resource out - https://docs.oracle.com/javase/tutorial/networking/sockets/index.html but if you need something specefic to nodejs this might interest you https://www.npmjs.com/package/socket.io & https://www.npmjs.com/package/socket.io-client – indranil32 Oct 23 '17 at 05:28
0

To access an HTTP resource in Java, you don't need to use the socket API, which is too low-level. You are not using it in the NodeJS client code.

import java.io.IOException;
import java.net.URL;
import java.util.Scanner;

public class Http {
    public static String get(String url) throws IOException {
        try (Scanner scanner = new Scanner(new URL(url).openStream())) {
            return scanner.useDelimiter("\\A").next();
        }
    }
}

Then you can use it like this:

try {
    String content = Http.get("http://localhost:8080/index.htm");
} catch (IOException e) {
    e.printStackTrace();
}
xiaofeng.li
  • 8,237
  • 2
  • 23
  • 30
  • I know that but I am trying to create a real time game so my first choice was nodeJS, and this code just for beginning and testing. – Khalid Ali Oct 23 '17 at 05:24
  • Try a different protocol then. Anyway, you shouldn't write HTTP code in Java if you're just "testing", it's a waste of time for your project. – xiaofeng.li Oct 23 '17 at 05:30
  • You should change your NodeJS server to not use the `http` library. Search `net.createServer`. – xiaofeng.li Oct 23 '17 at 05:31
  • What do you mean by "it's a waste of time for your project" ? and what should I learn to finish it ? @infgeoax – Khalid Ali Oct 23 '17 at 05:50