17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nodejs,websocketでチャット

Last updated at Posted at 2015-05-21

簡単なチャット
画面ソースがjadeなのはその時関心があったから

画面
doctype html
html(lang="ja")
  head
  body
    h1 easy chat
    input(type="text",id="message")
    button(type="button",id="submit") submit
    ul(id="messageList")

サーバーjs
var WebSocketServer = require('ws').Server;
var http = require('http');
var express = require('express');
var app = express();
var port = process.env.PORT || 5000;

//////////////////////
// setting http
app.use(express.static('public'));
app.set("views", "src");

app.get('/', function(req, res) {
  res.render('jade/chat.jade');
});

var server = http.createServer(app);
server.listen(port);
console.log("Node app is running at localhost:" + port);

///////////////////
// setting ws

var wss = new WebSocketServer({server:server});
console.log("websocket server created");

var connections = [];

// 接続開始
wss.on('connection', function(ws) {
  console.log('websocket connection open');

  connections.push(ws);
  /**
   * ws受信時
   * メッセージを受けたら、時間とuserIdを付与して、接続している全員にsend
   */
  ws.on('message', function(json) {
    console.log('message is ' + json);
    var data = JSON.parse(json);
    data.time = new Date();
    data.userId = connections.indexOf(ws) + 1;
    wss.clients.forEach(function(client) {
      client.send(JSON.stringify(data));
    });
  });

  // クローズ
  ws.on('close', function() {
    console.log('websocket connection close');
  });
});
フロントjs
var host = location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(host);
// ws受信
ws.onmessage = function(event) {
  var data = JSON.parse(event.data);
  switch (data.type) {
    // メッセージ
    case 'message':
      // 表示文字列作成
      var line = ""; 
      line += data.time;
      line += " ID:" + data.userId;
      line += " " + data.message;
      // リスト表示
      $('#messageList').append('<li>' + line + '</li>');
      break;
    default:
      break;
  }
};
// submitボタン押下
$('#submit').on('click', function() {
  var message = $('#message').val();
  if (message.length > 50) {
    return;
  }
  ws.send(JSON.stringify({
    type: 'message',
    message: message
  }));
});

ソースはこちら
https://github.com/yamatatsu/node-chat

17
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?