อะไรคือตัวอย่างของตัวอย่าง Socket.io ที่ง่ายที่สุดที่เป็นไปได้?


113

เมื่อเร็ว ๆ นี้ฉันพยายามทำความเข้าใจ Socket.io แต่ฉันไม่ใช่โปรแกรมเมอร์ที่ยอดเยี่ยมและเกือบทุกตัวอย่างที่ฉันสามารถหาได้บนเว็บ (เชื่อฉันว่าฉันดูมาหลายชั่วโมงแล้ว) มีสิ่งพิเศษที่ทำให้สิ่งต่าง ๆ ซับซ้อน มีตัวอย่างมากมายที่ทำให้ฉันสับสนหรือเชื่อมต่อกับฐานข้อมูลแปลก ๆ หรือใช้คอฟฟี่สคริปหรือไลบรารี JS จำนวนมากที่ทำให้ยุ่งเหยิง

ฉันชอบที่จะเห็นตัวอย่างการทำงานพื้นฐานที่เซิร์ฟเวอร์เพียงแค่ส่งข้อความไปยังไคลเอนต์ทุกๆ 10 วินาทีโดยบอกว่าเป็นเวลากี่โมงและลูกค้าจะเขียนข้อมูลนั้นลงในเพจหรือส่งการแจ้งเตือนซึ่งเป็นสิ่งที่ง่ายมาก จากนั้นฉันสามารถหาสิ่งต่างๆจากที่นั่นเพิ่มสิ่งที่ฉันต้องการเช่นการเชื่อมต่อ db เป็นต้นและใช่ฉันได้ตรวจสอบตัวอย่างในไซต์ socket.io แล้วและมันไม่ได้ผลสำหรับฉันและฉันไม่เข้าใจว่าพวกเขาทำอะไร .


4
มีอะไรผิดปกติกับตัวอย่างแรกที่ ( socket.io/#how-to-use ) ดูเหมือนง่ายสำหรับฉัน ...
maerics

1
สวัสดีมันช้าไปหน่อย แต่ใครก็ตามในอนาคตสามารถหาคำแนะนำดีๆได้ที่นี่ในการใช้ socketio กับ nodejs programmerblog.net/using-socketio-with-nodejs
Jason W

คำตอบ:


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

สิ่งนี้ไม่ได้ผลสำหรับฉัน ในเบราว์เซอร์ฉันได้รับหน้าว่าง ทางฝั่งเซิร์ฟเวอร์จะไม่มีเอาต์พุตยกเว้น "ไคลเอ็นต์ที่ได้รับอนุญาต" และ "แฮนด์เชคได้รับอนุญาต"
Boris

1
@Boris คุณอาจประสบปัญหานั้นหากคุณเปิดไฟล์ index.html ในเครื่อง หากคุณทำเช่นนั้นให้แทนที่แท็กสคริปต์ด้วย src = "http: // หากคุณโฮสต์บนเว็บเซิร์ฟเวอร์ให้เปิดคอนโซล javascript และพยายามระบุสิ่งที่ล้มเหลว
CodeMonkeyKing

4
ตอนแรกฉันได้รับ 'io ไม่ได้กำหนด' - ฉันใช้สิ่งนี้แทน <script src = " cdn.socket.io/socket.io-1.2.1.js " > </script > และตอนนี้ใช้งานได้
Alexander Mills

คุณควรเรียกใช้ "npm init" จากนั้นติดตั้ง socket io ผ่าน npm "npm install socket.io --save"
Farid Movsumov

31

นี่คือการส่งของฉัน!

หากคุณใส่รหัสนี้ลงในไฟล์ชื่อ hello.js และเรียกใช้โดยใช้โหนด hello.js มันควรพิมพ์ข้อความสวัสดีมันจะถูกส่งผ่าน 2 ซ็อกเก็ต

โค้ดแสดงวิธีจัดการกับตัวแปรสำหรับข้อความสวัสดีที่ถูกตีกลับจากไคลเอนต์ไปยังเซิร์ฟเวอร์ผ่านส่วนของโค้ดที่มีป้ายกำกับ // Mirror

ชื่อตัวแปรจะถูกประกาศแบบโลคัลแทนที่จะเป็นทั้งหมดที่ด้านบนเนื่องจากจะใช้ในแต่ละส่วนระหว่างความคิดเห็นเท่านั้น แต่ละไฟล์อาจอยู่ในไฟล์แยกกันและเรียกใช้เป็นโหนดของตัวเอง

// 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);


ฉันคิดว่านี่ควรเป็นทางออกที่ได้รับการยอมรับ อย่างน้อยก็ช่วยฉัน
Daft Fox

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 ซึ่งจะเห็นได้ชัดว่าเซิร์ฟเวอร์ของเราทำงานโดยโหนด ใส่รหัสต่อไปนี้ลงไป:

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

หากคุณเปิดเว็บเบราว์เซอร์และชี้ไปที่ชื่อโฮสต์ที่คุณกำลังเรียกใช้กระบวนการโหนดคุณจะเห็นตัวเลขเดียวกันปรากฏในเบราว์เซอร์ของคุณพร้อมกับเบราว์เซอร์ที่เชื่อมต่ออื่น ๆ ที่กำลังดูหน้าเดียวกัน


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 webpagemhm ใช่ ... var app = http.createServer(- wut
Don Cheadle

1
มีประโยชน์มากคุณช่วยวันของฉัน ขอบคุณมาก. นี่เป็นคำตอบที่ง่ายที่สุดโดยไม่ต้องโหลดมากเกินไปใน node.js ตัวอย่างนี้ดีกว่าสำหรับผู้เริ่มต้นทุกคนในการเริ่มต้นและทำความคุ้นเคยกับโหนด ขอขอบคุณอีกครั้ง
Karthik Elumalai

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/พอร์ตอาจแตกต่างกัน และคุณจะเห็นOUTPUTนี้

ใส่คำอธิบายภาพที่นี่

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.