使用java连接到localhost但没有任何反应,但它适用于nodejs客户端文件

时间:2017-10-23 04:21:43

标签: java node.js sockets server localhost

我正在尝试使用java应用程序连接到localhost,并且我有一个带有nodeJS的服务器端代码。这是我第一次处理nodeJS,当我创建server.js和client.js时,每件事都在工作正确,我可以发送和接收服务器的消息,但当我尝试使用Java代码(套接字)没有发生任何事情,但没有错误。我找不到原因,这是我第一次使用nodeJS,所以我觉得卡住了,任何人都可以给我建议或者找出我的错误。

这是我的java代码

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();
    }

这是我的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/');

这是我的nodeJS客户端代码,它工作正常

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();

2 个答案:

答案 0 :(得分:2)

试试这个......

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();
}

答案 1 :(得分:0)

要使用Java访问HTTP资源,您不需要使用太低级别的套接字API。您没有在NodeJS客户端代码中使用它。

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();
        }
    }
}

然后你可以像这样使用它:

try {
    String content = Http.get("http://localhost:8080/index.htm");
} catch (IOException e) {
    e.printStackTrace();
}