prosource

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

probook 2023. 7. 27. 22:05
반응형

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

그래서 저는 최근에 Socket.io 을 이해하려고 노력하고 있지만, 저는 대단한 프로그래머가 아닙니다. 그리고 제가 웹에서 찾을 수 있는 거의 모든 예(몇 시간 동안 찾아본 예를 제외하고)는 상황을 복잡하게 만드는 추가적인 것들을 가지고 있습니다.많은 예들이 저를 혼란스럽게 하거나, 이상한 데이터베이스에 연결하거나, 커피 스크립트나 많은 JS 라이브러리를 사용하여 일을 혼란스럽게 합니다.

저는 기본적으로 작동하는 예를 보고 싶습니다. 서버가 10초마다 클라이언트에게 몇 시인지 알려주는 메시지를 보내고 클라이언트는 그 데이터를 페이지에 쓰거나 경고를 표시합니다. 매우 간단한 것입니다.그러면 거기서 물건을 파악하고, DB 연결 등 필요한 것들을 추가할 수 있습니다.그리고 예, socket.io 사이트에서 예제를 확인했는데 제게 적합하지 않습니다. 그리고 저는 그들이 무엇을 하는지 이해할 수 없습니다.

편집: 소켓의 훌륭한 채팅 예를 참조하는 것이 누구에게나 좋다고 생각합니다.IO 시작 페이지입니다.제가 이 답변을 드린 이후로 API가 상당히 간소화되었습니다.그렇긴 하지만, 여기 새로운 API를 위해 소규모로 업데이트된 원래 답변이 있습니다.

색인.

<!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라는 파일에 넣고 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);

아마 이것도 당신에게 도움이 될 것입니다.저는 socket.io 의 작동 방식을 이해하는 데 어려움을 겪었기 때문에 가능한 한 예제를 요약하려고 했습니다.

저는 여기에 게시된 예를 다음과 같이 적용했습니다. http://socket.io/get-started/chat/

먼저 빈 디렉토리에서 시작하여 패키지라는 매우 간단한 파일을 만듭니다.json 그 안에 다음을 넣습니다.

{
"dependencies": {}
}

그런 다음 명령줄에서 npm을 사용하여 이 예제에 필요한 종속성을 설치합니다.

$ npm install --save express socket.io

네트워크 연결 속도/CPU/ 등에 따라 몇 분 정도 걸릴 수 있습니다.모든 것이 계획대로 진행되었는지 확인하기 위해 패키지를 보면 됩니다.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

웹 브라우저를 열고 노드 프로세스를 실행 중인 호스트 이름을 가리킬 경우 브라우저에 동일한 번호가 표시되고 연결된 다른 브라우저에서도 동일한 페이지를 볼 수 있습니다.

저는 이 직책이 지금 몇 년째라는 것을 알고 있지만, 때때로 저와 같은 인증된 신입사원들은 절대적으로 가장 간단한 형태로 완전히 분해된 작업 사례가 필요합니다.

내가 찾을 수 있는 모든 간단한 socket.io 예는 http.createServer()와 관련이 있습니다. 하지만 만약 당신이 기존 웹페이지에 socket.io 마법의 일부를 포함하고 싶다면 어떨까요?여기 제가 생각해 낼 수 있는 가장 쉽고 작은 예가 있습니다.

콘솔에서 UpperCASE로 전달된 문자열만 반환합니다.

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.dll:

<!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.dll을 찾아 브라우저 콘솔을 사용하여 메시지를 서버로 다시 보냅니다.

기껏해야 http.createServer를 사용할 때 다음 두 줄이 변경됩니다.

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

저는 이 매우 간단한 예를 통해 제 동료 신입생들이 고생하는 것을 조금이나마 덜 수 있기를 바랍니다. 그리고 제가 소켓 정의에 사용자 정의 변수 이름처럼 보이는 "유저 워드"를 사용하는 것을 멀리했다는 것을 알아두시기 바랍니다.

색인.

<!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/포트가 다를 수 있습니다. 그러면 이 출력이 표시됩니다.

enter image description here

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

반응형