Hatena::Groupbabel

カーネルハッカーを目指す男の日記

 | 

2014-11-23

websocketでチャットを作った

05:10

websocket熱が再び出てきたので、簡単なチャットを作ってみた。

(ローカルの設定は適宜変更)

サーバー

var http = require('http');
var WSServer = require('websocket').server;
var fs = require('fs');
var url = require('url');
var path = require('path');
var indexHtml = fs.readFileSync('index.html');

var documentRoot = '/usr/local/node/seagull2';

var mimeTypes = {
	'.js' : 'text/javascript',
	'.html' : 'text/html',
	'.css' : 'text/css',
};

var plainHttpServer = http.createServer(function (req, res) {
	var methodType = req.method;
	if (methodType == 'GET') {
		doGet(req, res);
	} else if (methodType == 'POST') {
		doPost(req, res);
	}
}).listen(1337);

function doGet(req, res) {
	var headers;
	var reqUrl = decodeURI(req.url);

	if (reqUrl === '/') {
		headers = {
			'content-Type' : 'text/html'
		};
		res.writeHead(200, headers);
		res.end(indexHtml);
	} else if (reqUrl === '/favicon.ico') {
		return;
	} else {
		var filename = documentRoot + reqUrl;
		var data = fs.readFileSync(filename);
		headers = {
			'Content-Type' : mimeTypes[path.extname(filename)]
		};
		res.writeHead(200, headers);
		res.end(data);
	}
}

function doPost(req, res) {
	var reqUrl = decodeURI(req.url);

	// TODO
	return;
}

var webSocketServer = new WSServer({
				httpServer : plainHttpServer
			});

var connections = [];
webSocketServer.on('request', function(req) {
	req.origiin = req.origin || '*';
	var websocket = req.accept(null, req.origiin);
	connections.push(websocket);
	websocket.on('message', function(data) {
		var param = JSON.parse(data.utf8Data);
		var name = param['name'];
		var message = param['message'];
		var text = name + " : " + message;
		for (var i = 0; i < connections.length; i++) {
			if (!connections[i].closed) {
				connections[i].sendUTF(text);
			}
		}
	});

	websocket.on('close', function(code, desc) {
		console.log('connection closed. : ' + code + ' - ' + desc);
	});
});

クライアント

var ws;

$(document).ready(function() {
	ws = new WebSocket("ws://192.168.11.3:1337");
	ws.onmessage = function(e) {
		var data = e.data;
		$("#messageBody").append("<p>" + data + "</p>");
	};
	ws.onclose = function(e) {
		console.log("connection closed. ", e.code + ' - ' + e.type);
	};
});

function sendMessage() {
	var name = $("#name").val();
	var message = $("#input_message").val();
	$("#input_message").val("");
	var param = {};
	param['name'] = name;
	param['message'] = message;
	ws.send(JSON.stringify(param));
}

画面

<!DOCTYPE HTML>
<html lang="ja">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>test</title>
	<meta name="viewport" content="width=device-width, initial-scale=0.6">
	<meta name="description" content="">
	<meta name="author" content="">
	<link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">
        <link href="lib/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet">
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
	<script type="text/javascript" src="lib/screen.js"></script>
	</head>
	<body>
		<div id="title">simple chat</div>
		<div class="container-fulid">
			<div class="row-fluid">
				<div class="span4">			
					<div class="well sidebar-nav">
						<ul class="nav nav-list">
							<li>
								<input id="name" type="text" placeholder="nickname" width="20">
							</li>
							<li>
								<div class="input">
									<textarea class="xxlarge" id="input_message" placeholder="message"></textarea>
								</div>
							</li>
							<li>
								<button id="send_message" type="submit" class="btn" onclick='sendMessage()'>send message</button>
							</li>
						</ul>
					</div>
				</div>
			</div>
		</div>
		<div id="messageArea" class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
			<div class="panel-heading">Messages</div>
				<div id="messageBody" class="panel-body">
			</div>
		</div>
	</body>
</html>

websocketって、もっと使いこなせたらかなり面白い事できると思うんだよなー。

ていうか全然関係無い作業してしまった。

怒られる。

 |