【发布时间】:2017-07-23 18:40:37
【问题描述】:
我正在尝试将一个简单的 Java 客户端连接到 NodeJS 服务器,但不幸的是,事情并没有那么顺利。我从 Java Doc 中获取了客户端代码,只更改了主机名和端口。现在我的服务器与客户端在同一台计算机上运行,端口为 4555。如果我在客户端和服务器上没有相同的端口,则会引发错误,我已经检查过了。此外,如果我在客户端将主机名更改为任意名称(不是 localhost),则会引发错误。这表明如果我无法连接,则会引发错误。有趣的是,如果我将端口设置为 4555 并将主机名设置为“localhost”,我不会收到任何这些错误,而且我的客户端工作正常,这让我认为我正在建立连接,但我没有得到在我的服务器端消息“客户端已连接”。有什么建议吗?
服务器代码:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 4555;
app.get('/', function(req, res)
{
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket)
{
//When I connect to to localhost:4555 through the web browser(chrome)
//this message is actually shown so the connection works there.
console.log('client connected');
});
http.listen(port, function()
{
//Message shown on program start
console.log("app running");
});
客户端代码:
import java.io.*;
import java.net.*;
public class Main
{
public static void main(String[] args) throws IOException
{
String hostName = "localhost";
int portNumber = 4555;
try (
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
) {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
【问题讨论】:
-
为什么不使用 ApacheHTTPClient 库从您的 Java 客户端发出请求?
-
使用8000以上的端口号。
-
你有一个客户端和一个服务器。你的服务器需要监听客户端连接的端口,客户端需要连接服务器监听的端口。除此之外,我不知道哪个错误来自服务器,哪个来自客户端。主机名也不是任意的,它必须解析为合理的。
标签: java node.js sockets socket.io