簡體   English   中英

第一次使用socket.io

[英]Using socket.io for the first time

我正在嘗試制作一個使用Javascript和Node.js的Web應用程序。 我需要從Javascript調用Node.js,因為我必須能夠傳遞參數,並且直到通過傳單事件后才能擁有它們。 我正在嘗試使用Socket.io傳遞那些參數,但無法使其正常工作。 這是我的測試代碼,不起作用。 有人可以幫我弄清楚為什么它不起作用嗎?

PS。 我在個人php和Node.js服務器上運行。

客戶端 :

    <script>
        var socket = io.connect('localhost');
        socket.on('news', function (data){
            console.log(data);
            socket.emit('my other event', {my: 'data'});
        });
    </script>
</body>

服務器端 :

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
   socket.emit('news', {hello: 'world'});

   socket.on('my other event', function (data) {
      console.log(data); 
   });
});

來自瀏覽器的錯誤錯誤

它使用起來非常簡單,我為您提供了一個頁面,其中逐步向您展示了如何使用框架。

https://socket.io/get-started/chat/

以及它對應的倉庫顯示了如何使用示例。

https://github.com/socketio/chat-example

基本上,您必須做。

git clone https://github.com/socketio/chat-example.git

npm install

npm start

我將更改index.js文件以了解消息的去向

index.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    // This is the additional line
    console.log(msg);
    io.emit('chat message', msg);
  });
});

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

如果出現cors錯誤,請添加到index.js文件中。

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

看起來像是跨源請求錯誤。

看一下CORS中間件以進行快速表達。

本質上,您是從其他域發送請求,而沒有明確表示允許其他域訪問您的服務器,因此該服務器拒絕訪問。

本質上,您需要的是請求上的訪問控制標頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM