我正在建立Socket Server(Java)和Socket Client(NodeJS)之间的实时连接。这是用于Web界面的。
我可以将数据从NodeJS发送到Java,但不能反过来。我在代码中评论了我的意思。我已经尝试过使用 out.write(“ Hello World \ n”); 进行操作,就像您看到的一样(当然有冲洗)。我也尝试过使用 out.println(“ Hello World”); (当然有同花顺)。
public class WebHandler {
private ServerSocket server;
private static Socket sock;
public void listen(int port) {
try {
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Could not listen on port " + port);
System.exit(-1);
}
Bukkit.getScheduler().scheduleSyncRepeatingTask(Main.getPlugin(), new BukkitRunnable() {
@Override
public void run() {
try {
System.out.println("Waiting for connection");
final Socket socket = server.accept();
sock = socket;
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);
}
WebHandler.sendMessage();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
}
}, 0, 100);
}
// CRITICAL
public static void sendMessage() {
try {
PrintWriter out = new PrintWriter(sock.getOutputStream());
out.write("Hello World from Java!" + "\n");
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
var net = require('net');
var client = net.connect(9090, 'localhost');
client.setEncoding('utf8');
setInterval(function() {
console.log("Writing....")
var ret = client.write('Hello from node.js\n');
console.log("Wrote", ret)
}, 5000);
// CRITICAL
client.on('data', function(data) {
console.log('Received: ' + data);
});
请不要因为Bukkit.getScheduler()而分心,它只是一个任务管理器。在此先感谢:D
答案 0 :(得分:0)
您没有收到来自Java的消息,因为您设置了一个间隔,该间隔将始终向服务器发送消息,并且服务器将陷入while循环中。
我建议在某个时间点停止间隔,以便调用sendMessage()。