繁体   English   中英

将套接字连接到特定路径

[英]connecting socket to a specific path

我有一个路径 localhost:3000/home 我想通过 socket.io 将消息传递到该路径。

我的js文件

var express = require('express');
var app = express();
var http = require('http').Server(app);
var path = require("path");
var io = require('socket.io')(http);


app.get('*', function (req, res){
  res.sendFile(path.join(__dirname, '/Public'));
});

app.use('/home',express.static(path.join(__dirname,'/Public')));

//app.use('/static', express.static(__dirname + 'index.html'));

io.on('connection', function (socket) {
  socket.on('message', function (data) {
  console.log(data)
  socket.emit('news', { hello: 'world' });
   });
    socket.on('another-message', function (data) {
    socket.emit('not-news', { hello: 'world' });
  });
});
 


http.listen(3000, function(){
  console.log('listening on *:3000');
});

我的 html 文件

<html>
<h1>working</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
  var ioPath = "";
  iopath = '/' + 'home'+ '/socket.io'
  var socket = io.connect('http://localhost:3000', { path : iopath});
  //var socket = io.connect('http://localhost:3000');
    socket.on('connect',function(){
    socket.emit('message',{ 'msg' :'Hello server'}); 
    //socket.emit('message', 'Hello server');
  });
   socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>
<body>
    <ul id="messages"></ul>
    <form id ="target" action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>

我在浏览器控制台中收到以下错误:“GET http://localhost:3000/home/socket.io/?EIO=3&transport=polling&t=LA2Fcjf 404 (Not Found)”

请纠正我。

试试这个

var io = require('socket.io')(http,{ path: '/home/socket.io'});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM