【发布时间】:2014-04-11 11:29:25
【问题描述】:
我有一个用 node.js 编写的简单套接字服务器:
var net = require("net");
var clients = [];
net.createServer(function(socket){
//Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort;
//Put this new client in the list
clients.push(socket);
//Send welcome message
socket.write("Welcome " + socket.name + "\n");
broadcast(socket.name + " joined the room \n");
//Handle incoming messages from clients
socket.on('data', function(data){
broadcast(socket.name + "> " + data, socket);
});
//Remove client when it leaves
socket.on('end', function(){
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " left the chat.\n");
});
socket.on('error', function(err){
console.log(err);
});
function broadcast(message, sender){
clients.forEach(function(client){
if(client === sender) return;
client.write(message);
});
console.log(message);
}
}).listen(5000);
console.log("Chat server running at port 5000\n");
如您所见,此套接字服务器能够识别事件{'error', 'end', 'data'},如果我愿意,我可以定义更多!
我的问题是,如何在 Java 中向它发送事件?
这是一个简单的 TCP-Client I found online here:
import java.lang.*;
import java.io.*;
import java.net.*;
class Client {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
while (!in.ready()) {}
System.out.println(in.readLine()); // Read one line and output it
System.out.print("'\n");
in.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
在这段代码中,我将如何更改它以便我可以发送事件,例如
{'error', 'end', 'data'}
【问题讨论】:
-
'error'/'end'/'data' 事件是 NodeJS 中定义的 IO 事件。 java中没有这样的东西。如果您在 nodejs 中向服务器套接字发送任何数据,则会触发“数据”事件。套接字关闭时触发的 'end' 事件。