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

Coc*_*ico 107 node.js socket.io

所以,我最近一直试图理解Socket.io,但我不是一个超级好的程序员,几乎我在网上找到的每一个例子(相信我,我已经看了几个小时),有额外的东西使事情变得复杂.很多例子做了很多混淆我的事情,或连接到一些奇怪的数据库,或使用coffeescript或大量混乱的JS库.

我希望看到一个基本的功能示例,其中服务器每10秒向客户端发送一条消息,说明它是什么时间,客户端将该数据写入页面或引发警报,非常简单.然后我可以从那里找出事情,添加我需要的东西,如数据库连接等等.是的,我已检查socket.io网站上的示例,他们不适合我,我不明白他们做什么.

Lin*_*iel 147

编辑:我觉得任何人都可以在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>
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

  • 最初我得到'我没有定义' - 我使用它而不是<script src ="https://cdn.socket.io/socket.io-1.2.1.js"> </ script>现在它的工作原理 (4认同)

小智 27

这是我的提交!

如果你把这个代码放到一个名为hello.js的文件中并使用节点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);
Run Code Online (Sandbox Code Playgroud)


小智 19

也许这对你也有帮助.我在查看socket.io如何工作时遇到了一些麻烦,所以我试着尽可能多地烧掉一个例子.

我在此处发布的示例中修改了此示例:http://socket.io/get-started/chat/

首先,从一个空目录开始,创建一个名为package.json的非常简单的文件.将以下内容放入其中.

{
"dependencies": {}
}
Run Code Online (Sandbox Code Playgroud)

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

$ npm install --save express socket.io
Run Code Online (Sandbox Code Playgroud)

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

$ cat package.json
{
  "dependencies": {
    "express": "~4.9.8",
    "socket.io": "~1.1.0"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

创建名为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>
Run Code Online (Sandbox Code Playgroud)

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

$ node server.js
listening on *:3001
0.9575486415997148
0.7801907607354224
0.665313188219443
0.8101786421611905
0.890920243691653
Run Code Online (Sandbox Code Playgroud)

如果您打开一个Web浏览器,并将其指向您正在运行节点进程的主机名,您应该会在浏览器中看到相同的数字,以及查看同一页面的任何其他连接的浏览器.


edw*_*rkf 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
    });

});
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

跑步:

npm init;  // accept defaults
npm  install  socket.io  http  --save ;
node app.js  &
Run Code Online (Sandbox Code Playgroud)

使用类似此端口测试的东西来确保您的端口是开放的.

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

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

<script type='text/javascript' src='/socket.io/socket.io.js'></script>
var socket = io();
Run Code Online (Sandbox Code Playgroud)

我希望这个非常简单的例子可以让我的新手们有些挣扎.请注意我没有使用"保留字"查找用户定义的变量名称作为我的套接字定义.

  • `每个简单的socket.io示例我都能找到http.createServer().但是如果你想在现有的网页中包含一些socket.io魔术呢?mhm是的...`var app = http.createServer(` - wut (3认同)