socket.io進階 雙人聊天室舉例

//服務端css

// Setup basic express server
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').createServer(app);
var io = require('../..')(server);
var port = process.env.PORT || 8080;

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

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

io.on('connection', function (socket) {
    var url = socket.request.headers.referer;
    //room 根據具體的生成或者添加
    var room=url.split('room_id')[1].substring(1);
    socket.join(room);
    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
    socket.on('new message', function (data) {
        io.to(room).emit('receive message',data );
    });
});

 

//客戶端html

index.htmljquery

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Socket.IO Chat Example</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
<input class="input" type="text" maxlength="14" />
<button id="bbb">點擊發送消息</button>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="/main.js"></script>
</body>
</html>

 

main.jsexpress

$(function() {
  var socket = io();
  $('#bbb').click(function(){
      var message=$('.input').val()
      if(message){
          socket.emit('new message',message)
      }else{
          alert('請輸入信息')
      }

  })

    socket.on('receive message', function (data) {
        console.log(data);
    });
});

 

npm installnpm

npm startapp

打開2個連接:socket

localhost:8080/?room_id=%27room1%27     ui

 

相關文章
相關標籤/搜索