最简单的Socket.io示例的示例是什么?


113

因此,我最近一直试图了解Socket.io,但是我不是一个非常出色的程序员,并且几乎可以在网上找到每个示例(相信我已经花了数小时的时间),还有一些使事情变得复杂的东西。许多示例都会使我感到困惑,或者连接到一些奇怪的数据库,或者使用coffeescript或大量的JS库将事情弄乱。

我很乐意看到一个基本的,可以正常运行的示例,其中服务器仅每10秒向客户端发送一条消息,说明现在几点,然后客户端将数据写入页面或引发警报,这很简单。然后,我可以从那里弄清楚事情,添加数据库连接之类的我需要的东西。是的,我已经检查了socket.io网站上的示例,它们对我不起作用,我也不知道它们在做什么。


4
socket.io/#how-to-use)的第一个示例有什么问题?对我来说似乎很简单……
maerics 2012年

1
嗨,它有点晚了,但是以后任何人都可以在这里找到将socketio与nodejs一起使用的好教程。developerblog.net/using-socketio-with-nodejs
Jason W'J

Answers:


154

编辑:我觉得最好让任何人在Socket.IO入门页面上咨询出色的聊天示例。自从我提供了这个答案以来,API已经被简化了。就是说,这是针对较新的API的原始答案(由小到小)。

只是因为我今天感觉很好:

index.html

<!doctype html>
<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io();

            socket.on('welcome', function(data) {
                addMessage(data.message);

                // Respond with a message including this clients' id sent from the server
                socket.emit('i am client', {data: 'foo!', id: data.id});
            });
            socket.on('time', function(data) {
                addMessage(data.time);
            });
            socket.on('error', console.error.bind(console));
            socket.on('message', console.log.bind(console));

            function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
            }
        </script>
    </head>
    <body>
        <ul id='messages'></ul>
    </body>
</html>

app.js

var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function(socket) {
    // Use socket to communicate with this particular client only, sending it it's own id
    socket.emit('welcome', { message: 'Welcome!', id: socket.id });

    socket.on('i am client', console.log);
});

app.listen(3000);

非常感谢,这当然是有效的,更重要的是,我开始了解它是如何工作的。你们很高兴写这篇文章,老实说,我确实花了至少3到4个小时来尝试使所有这些都能正常工作,真是可悲。非常感谢Linus!
Cocorico'3

这对我不起作用。在浏览器中,我得到一个空白页。在服务器端,除了“客户端授权”和“握手授权”外,没有输出。
鲍里斯(Boris)2013年

1
@Boris,如果您在本地打开index.html文件,则可能会遇到该问题。如果你没有,然后用SRC =“HTTP更换脚本标记://如果您在Web服务器上托管然后打开JavaScript控制台,并尝试找出失败的原因。
CodeMonkeyKing

4
最初我得到的是“未定义的io”-我改用了<script src =“ cdn.socket.io/socket.io-1.2.1.js" > </script >,现在可以使用了
Alexander Mills

您应该运行“ npm init”,然后通过npm“ npm install socket.io --save”安装套接字io
Farid Movsumov

31

这是我的意见书!

如果将此代码放入名为hello.js的文件中,并使用node hello.js运行它,则应打印出消息hello,它已通过2个套接字发送。

该代码显示了如何处理标记为// Mirror的代码部分从客户端向服务器退回的Hello消息的变量。

变量名在本地声明,而不是在顶部声明,因为它们仅在注释之间的每个部分中使用。这些中的每一个都可以在单独的文件中并作为其自己的节点运行。

// Server
var io1 = require('socket.io').listen(8321);

io1.on('connection', function(socket1) {
  socket1.on('bar', function(msg1) {
    console.log(msg1);
  });
});

// Mirror
var ioIn = require('socket.io').listen(8123);
var ioOut = require('socket.io-client');
var socketOut = ioOut.connect('http://localhost:8321');


ioIn.on('connection', function(socketIn) {
  socketIn.on('foo', function(msg) {
    socketOut.emit('bar', msg);
  });
});

// Client
var io2 = require('socket.io-client');
var socket2 = io2.connect('http://localhost:8123');

var msg2 = "hello";
socket2.emit('foo', msg2);


我认为这应该是公认的解决方案。至少对我有帮助。
达夫·福克斯

21

也许这对您也有帮助。我很难理解socket.io的工作原理,所以我尝试尽我所能。

我从此处发布的示例改编了该示例:http : //socket.io/get-started/chat/

首先,从一个空目录开始,然后创建一个名为package.json的非常简单的文件。

{
"dependencies": {}
}

接下来,在命令行上,使用npm安装此示例所需的依赖项

$ npm install --save express socket.io

这可能需要几分钟,具体取决于网络连接/ CPU /等的速度。要检查一切是否按计划进行,可以再次查看package.json文件。

$ cat package.json
{
  "dependencies": {
    "express": "~4.9.8",
    "socket.io": "~1.1.0"
  }
}

创建一个名为server.js的文件, 这显然是我们的服务器,由node运行。将以下代码放入其中:

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

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

http.listen(3001, function(){

  console.log('listening on *:3001');

});

//for testing, we're just going to send data to the client every second
setInterval( function() {

  /*
    our message we want to send to the client: in this case it's just a random
    number that we generate on the server
  */
  var msg = Math.random();
  io.emit('message', msg);
  console.log (msg);

}, 1000);

创建最后一个名为index.html的文件,并将以下代码放入其中。

<html>
<head></head>

<body>
  <div id="message"></div>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();

    socket.on('message', function(msg){
      console.log(msg);
      document.getElementById("message").innerHTML = msg;
    });
  </script>
</body>
</html>

现在,您可以测试这个非常简单的示例,并看到一些类似于以下内容的输出:

$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653

如果打开Web浏览器,并将其指向运行节点进程的主机名,则应该在浏览器中看到相同的数字,以及与该页面相同的所有其他连接的浏览器。


10

我意识到这篇文章已经有几年历史了,但是有时候像我这样的认证新手需要一个可以完全简化为绝对最简单形式的工作示例。

我能找到的每个简单的socket.io示例都涉及http.createServer()。但是,如果您想在现有网页中加入一点socket.io魔术,该怎么办?这是我能想到的绝对最简单和最小的例子。

这只是返回从控制台UPPERCASED传递的字符串。

app.js

var http = require('http');

var app = http.createServer(function(req, res) {
        console.log('createServer');
});
app.listen(3000);

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


io.on('connection', function(socket) {
    io.emit('Server 2 Client Message', 'Welcome!' );

    socket.on('Client 2 Server Message', function(message)      {
        console.log(message);
        io.emit('Server 2 Client Message', message.toUpperCase() );     //upcase it
    });

});

index.html:

<!doctype html>
<html>
    <head>
        <script type='text/javascript' src='http://localhost:3000/socket.io/socket.io.js'></script>
        <script type='text/javascript'>
                var socket = io.connect(':3000');
                 // optionally use io('http://localhost:3000');
                 // but make *SURE* it matches the jScript src
                socket.on ('Server 2 Client Message',
                     function(messageFromServer)       {
                        console.log ('server said: ' + messageFromServer);
                     });

        </script>
    </head>
    <body>
        <h5>Worlds smallest Socket.io example to uppercase strings</h5>
        <p>
        <a href='#' onClick="javascript:socket.emit('Client 2 Server Message', 'return UPPERCASED in the console');">return UPPERCASED in the console</a>
                <br />
                socket.emit('Client 2 Server Message', 'try cut/paste this command in your console!');
        </p>
    </body>
</html>

跑步:

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node app.js  &

使用类似此端口测试的方法来确保您的端口是开放的。

现在浏览到http://localhost/index.html并使用浏览器控制台将消息发送回服务器。

最好的猜测是,在使用http.createServer时,它将为您更改以下两行:

<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();

我希望这个非常简单的例子可以使我的新手同伴省事。并且请注意,我没有使用“保留字”查找用户定义的变量名作为套接字定义。


3
every simple socket.io example i could find involved http.createServer(). but what if you want to include a bit of socket.io magic in an existing webpagevar app = http.createServer(- 是的
Don Cheadle

1
非常非常有用,您保存了我的一天。非常感谢。这是最简单的答案,并且不会在node.js中加载太多,这个示例对于所有初学者来说都可以更好地开始并熟悉node。再次感谢您
KARTHIK埃卢马莱

0

index.html

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
      #messages { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        var socket = io();
        $('form').submit(function(){
          socket.emit('chat message', $('#m').val());
          $('#m').val('');
          return false;
        });
        socket.on('chat message', function(msg){
          $('#messages').append($('<li>').text(msg));
          window.scrollTo(0, document.body.scrollHeight);
        });
      });
    </script>
  </body>
</html>

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){
    io.emit('chat message', msg);
  });
});

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

运行这些命令以运行应用程序。

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node start

并打开URL:- http://127.0.0.1:3000/端口可能不同。你会看到这个输出

在此处输入图片说明

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.