Programming

가장 간단한 Socket.io 예제의 예는 무엇입니까?

procodes 2020. 8. 9. 10:56
반응형

가장 간단한 Socket.io 예제의 예는 무엇입니까?


그래서 저는 최근에 Socket.io를 이해하려고 노력했지만 저는 훌륭한 프로그래머가 아니며 웹에서 찾을 수있는 거의 모든 예제 (저는 몇 시간이고 몇 시간 동안 찾아 봤다고 믿습니다)에는 상황을 복잡하게 만드는 추가 항목이 있습니다. 많은 예제가 나를 헷갈 리게하거나 이상한 데이터베이스에 연결하거나 커피 스크립트 또는 일을 복잡하게 만드는 수많은 JS 라이브러리를 사용합니다.

서버가 10 초마다 클라이언트에게 메시지를 보내고 시간을 알려주고 클라이언트가 해당 데이터를 페이지에 쓰거나 매우 간단한 경고를 표시하는 기본적인 작동 예제를보고 싶습니다. 그런 다음 거기에서 알아낼 수 있고, db 연결과 같은 필요한 것을 추가 할 수 있습니다. 그리고 예, socket.io 사이트에서 예제를 확인했지만 저에게 적합하지 않으며 그들이 무엇을하는지 이해하지 못합니다. .


편집 : 누구나 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);

여기 내 제출입니다!

이 코드를 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);


아마도 이것은 당신에게도 도움이 될 것입니다. socket.io가 작동하는 방식에 머리를 감는 데 어려움을 겪고 있었기 때문에 가능한 한 예제를 끓여 보았습니다.

여기에 게시 된 예제에서이 예제를 수정했습니다. http://socket.io/get-started/chat/

First, start in an empty directory, and create a very simple file called package.json Place the following in it.

{
"dependencies": {}
}

Next, on the command line, use npm to install the dependencies we need for this example

$ npm install --save express socket.io

This may take a few minutes depending on the speed of your network connection / CPU / etc. To check that everything went as planned, you can look at the package.json file again.

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

Create a file called server.js This will obviously be our server run by node. Place the following code into it:

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

Create the last file called index.html and place the following code into it.

<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>

You can now test this very simple example and see some output similar to the following:

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

If you open up a web browser, and point it to the hostname you're running the node process on, you should see the same numbers appear in your browser, along with any other connected browser looking at that same page.


i realize this post is several years old now, but sometimes certified newbies such as myself need a working example that is totally stripped down to the absolute most simplest form.

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 webpage? here is the absolute easiest and smallest example i could come up with.

this just returns a string passed from the console 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>

to run:

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

use something like this port test to ensure your port is open.

now browse to http://localhost/index.html and use your browser console to send messages back to the server.

at best guess, when using http.createServer, it changes the following two lines for you:

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

i hope this very simple example spares my fellow newbies some struggling. and please notice that i stayed away from using "reserved word" looking user-defined variable names for my socket definitions.

참고URL : https://stackoverflow.com/questions/9914816/what-is-an-example-of-the-simplest-possible-socket-io-example

반응형