我在docker容器上运行了一个简单的应用程序。此容器不会一直运行。它开始,做某些工作并停止。当它启动时,我想通过socket.io将它连接到服务器。我曾尝试使用socket.io-client
,但仍无法使其正常运行。这是我的应用代码:
var docker_host_ip = process.env.DOCKER_HOST_IP;
var address = 'http://' + docker_host_ip +":" + port;
console.log("console : " + address);
var socket = require('socket.io-client')(address);
socket.on("disconnect", function(){
console.log("disconnected ");
});
socket.on("connect_failed", function(err){
console.log("err : " + err);
});
socket.on('connect', function(){
console.log("connected");
});
socket.on('news', function(data){
console.log("data : " + data);
socket.emit("news", {docker: "This is docker"});
});
socket.emit("news", {docker: "This is docker"});
socket.on('error', function (err) {
console.log(err);
});
我使用了这个https://github.com/socketio/socket.io-client。
var port = 4000;
app.use(express.static('.'))
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
socket.emit("news", {"hello": "hello"});
socket.on("news", function(data){
console.log( "new " + data);
io.sockets.emit("news", data);
});
socket.on('disconnect', function() {
console.log('Got disconnect!');
});
});
app.get("/", function(res, req){
req.sendFile(path.join('/index.html'));
});
http.listen(port, function(){
console.log('listening on *' + port);
});
我的应用未显示任何错误,但未发送消息。我的服务器通过浏览器正常工作(使用socket.io)。 有人可以告诉我有什么问题吗?
答案 0 :(得分:0)
你有两个相同的socket.emit消息名称,我想服务器首先发送消息。
服务器强>
socket.emit("news", {"hello": "hello"});
socket.on("news1", function(data){
console.log( "new " + data);
io.sockets.emit("news2", data);
});
<强>客户端强>
socket.on('news', function(data){
console.log("data : " + data);
socket.emit("news1", {docker: "This is docker"});
});
socket.on('news2', function(data){
console.log("data : " + data);
});