美文网首页
2018-10-24 起步socket.io

2018-10-24 起步socket.io

作者: 不知道取个什么昵称不如娶个媳妇 | 来源:发表于2018-10-24 20:00 被阅读0次

socket 套接字

使用socketio 需要安装express nodejsweb框架
--save --项目上线还需要的时候使用的指令
--save-dev 项目开发以后就不用使用的时候

// 引入 "express" 创建 Express 的应用实例
const app = require('express')();
// 基于 Express 应用实例来创建 webserver
const http = require('http').Server(app);
// 引入 "path" 模块
const path = require("path");

// 创建服务器端的 Socket 对象,绑定IP与端口
const io = require('socket.io')(http);

// 路由:当使用 GET 请求方式请求 "/" 资源时,执行回调函数
app.get('/', function(req, res){
  // 向响应流中发送文本数据
  // res.send('<h1>大家好</h1>');
  // 向响应流中发送文件数据
  res.sendFile(path.join(__dirname, "./index.html"));
});

// 监听客户端的 socket 连接,当有客户端连接上来,则触发 "connection" 事件函数的执行
io.on('connection', (socket) => {
  // socket 表示的是客户端的连接对象
  console.log('a user connected');
  // 绑定服务器端的事件,用于接收从客户端发送过来的消息
  socket.on("server", (msg) => {
    console.log('message: ' + msg);
    // 触发在客户端绑定的事件 "client",目的是向所有客户端发送消息
    io.emit('client', msg);
  });
});

// 监听
http.listen(3000, function(){
  console.log('listening on *:3000');
});

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 0 50px 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
  </head>
  <body>
    <!-- 显示聊天消息 -->
    <ul id="messages"></ul>

    <!-- 发送聊天消息的表单 -->
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        // 创建客户端的 Socket 对象,连接服务器
        var socket = io();
        // 处理表单提交事件
        $('form').submit(function(){
          // 触发在服务器端绑定的 "server" 事件,目的:向服务器发送消息
          socket.emit('server', $('#m').val());
          $('#m').val('');

          return false; // 阻止默认与冒泡
        });

        // 绑定客户端事件:接收服务器发送过来的消息
        socket.on("client", (msg) => {
          $('#messages').append($('<li>').text(msg));

          // 滚动到最后
          $("#messages").children().last().get(0).scrollIntoView();
        });
      });
      // $(document).ready(callback);
    </script>
  </body>
</html>

相关文章

网友评论

      本文标题:2018-10-24 起步socket.io

      本文链接:https://www.haomeiwen.com/subject/hyyttqtx.html