Tech Tips

  1. Uncategorized
  2. 123 view

[express][socket.io]Check it out that chat demo

Reference


※This article is just memo when I read the article above.

1.Receiver

It’s good that I write below on app.js because server side socket.io part listens for server.
"use strict";
var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);

var server = http.createServer(app);
server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

//=================================================================
//socket.ioのインスタンス作成
var io = require('socket.io').listen(server);

//クライアントから接続があった時
io.sockets.on('connection',function(socket){
	//クライアントからmessageイベントが受信した時
	socket.on('message',function(data){
		//念のためdataの値が正しいかチェック
		if(data && typeof data.text === 'string'){
			//メッセージを投げたクライアント以外全てのクライアントにメッセージを送信する。
			socket.broadcast.json.emit('message',{text:data.text});
		}
	});
});
I think it’s better that I write a model and “use” statement.

2.view

Next is client side.
At the article’s sample above, the view (routes/index.js’s view) load a javascript and proceed.
<!DOCTYPE html>
<html>
  <head>
    <title>チャットサンプル</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
<script src="/socket.io/socket.io.js"></script>
<script src="/javascripts/jquery-1.8.0.js"></script>
<script src="/javascripts/client.js"></script>
  </head>
  <body>
    <h1>チャットサンプル</h1>
    <div><input type="text" id="input" /><button id="send">send</button></div>
<div id="list"></div>
  </body>
</html>
jQuery(function($) {
	"use strict";
	//socket.ioのサーバにに接続
	var socket = io.connect('http://'+location.host+'/');

	//サーバからmessageイベントが送信された時
	socket.on('message',function(data){
		$('#list').prepend($('<div/>').text(data.text));
	});
	//sendボタンがクリックされた時
	$('#send').click(function(){
		var text = $('#input').val();
		if(text !== ''){
			//サーバにテキストを送信
			socket.emit('message',{text:text});
			$('#list').prepend($('<div/>').text(text));
			$('#input').val('');
		}
	});
});

3.Result

result

Uncategorized recent post

  1. Run Amazon FreeRTOS on M5Stack Core2 for AWS …

  2. Udacity Self-Driving Car Engineer Nanodegree …

  3. Install sbt 1.0.0 and run sample template

  4. Visualization of Neural Network and its Train…

  5. [Machine Learning]Created docker image includ…

関連記事

PAGE TOP