我正在尝试通过 Java 向我的 node.js/socket.io 服务器发送消息
这是我用来发送消息的代码
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
class socketMessage {
public socketMessage() {
}
public static void send(String string) throws Exception {
System.out.println("Sending message to Socket Server!");
URL url = new URL("http://<mysite>:8000");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
try (OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream())) {
System.out.println("Data Sent!");
writer.write(string);
writer.flush();
}
conn.getResponseCode(); // Thanks to BGR
}
}
调用:socketMessage.send("Admin|notification|Logged in elsewhere\n> Official Java App");
这是服务器代码:
var http = require("http");
var io = require('socket.io');
var sessionsConnections = {};
var whereIsUserVisitingFrom = {};
console.log("\n\n-------------------------------- Server Started --------------------------------");
var server = http.createServer(function(req, res){
var body = '';
req.on('data', function(data){
console.log('Received Data');
body += data;
});
req.on('end', function() {
// Emit the data to all clients
ioServer.emit('message', { message: body });
});
});
server.listen(8000);
var ioServer = io.listen(server, { log: false });
ioServer.on('connection', function(socket) {
var currentUser;
var parts;
socket.on('started', function(data) {
currentUser = data.username;
sessionsConnections[currentUser] = socket.id;
whereIsUserVisitingFrom[currentUser] = data.from;
socket.emit("connected", { message: "Welcome, " + currentUser + "!" });
socket.broadcast.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });
socket.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });
});
socket.on('message', function(data) {
var parts = data.message.split("|");
socket.broadcast.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });
socket.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });
console.log("Message Recieved!");
if( parts[0] == "*" ) {
socket.broadcast.emit("display", { message: data.message });
}else{
if( parts[0] in sessionsConnections ) {
io.sockets.socket(sessionsConnections[parts[0]]).emit("display", { message: data.message });
}else{
socket.emit("display", { message: "That user is not online!" });
}
}
});
socket.on('disconnect', function() {
delete sessionsConnections[currentUser];
socket.broadcast.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });
socket.emit("updateUsers", { message: sessionsConnections, from: whereIsUserVisitingFrom });
});
});
基本上我的服务器当前所做的是当我访问我的网站时,然后以“{user}|{action (ie notification)}|{text/extra_param(s)}”的形式从我的管理中心发送一个命令,它将发送向您设置为 {user} 的客户端发送一条消息,然后我在客户端有代码,该代码将该消息分成几部分并相应地更改网站 UI,但我也想从我的 Java 应用程序中执行此操作,并且它不工作:(
有任何想法吗
文尼
提前致谢