socket.io 记

作者:new 分类: 游戏服务器 发布于:2017-7-26 3:04 ė次浏览 6条评论
var express = require('express');
var path = require('path');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use(express.static(path.join(__dirname,'/public')));

io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('msg', function(data){
        console.log(data);
        socket.broadcast.emit('new msg', data);
    });
    socket.on('disconnect',function(){
        console.log('user disconnet');
    });
});

http.listen(3000, function(){
    console.log('listening on 3000');
});



前端

<!DOCTYPE html>
<html>
<head>
    <title>sk</title>
</head>
<script src="https://cdn.bootcss.com/socket.io/1.7.3/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>

<body>
test<br/>
<div id="content"></div>
<input type="text" id="msg">
<input type="button" id="send_btn" value="Send" >
</body>
<script>
  window.onload=function(){
    var socket = io.connect('http://127.0.0.1:3000');

    socket.on('new msg', function(data){
      console.log('<<'+data);
      $('#content').html($('#content').html()+'<br/>'+ data);
    });
    console.log("-------------");

    $('#send_btn').click(function(){
      socket.emit('msg', $('#msg').val());
      $('#msg').val('');
      return false;
    });
  }
</script>
</html>

本文出自 码农,转载时请注明出处及相应链接。

0

发表评论

电子邮件地址不会被公开。必填项已用*标注


Ɣ回顶部