node.jsとsocket.ioを使用する機会があったので、簡単にチャットを作ることにしました。
今回はユーザーに名前を付けてみます。
完成品だけ見たい場合は4を見てください
https://qiita.com/Catatataki/items/03ce43785466603dadac
作成イメージ
ディレクトリ
コード
hello.html
前回から変更なし
CSS追加
hello.CSS
.joincomment{
text-align:center;
}
.name{
display: inline-block;
font-size: 12px;
position: relative;
top:-35px;
left:90px;
}
JS変更
Line.js
var socket = io.connect('http://localhost:3000');
var name = prompt('ニックネームを入力してください', '');
joinUser(name);
socket.on("server_to_client", function (data) {
appendOtherMsg(data.otherMsg, data.name, data.img);
});
socket.on("server_to_client_join", function (data) {
appendJoinMsg(data.join);
});
function appendJoinMsg(message) {//参加退出コメント
$(".line").append('<div class="joincomment">' + message + '</div><br>');
$('.line').animate({ scrollTop: $('.line')[0].scrollHeight }, 'fast');
}
function appendOtherMsg(message, name) {//名前追加
$(".line").append('<div class="others"><span class="name">' + name + '</span><div class="othercomment"><p>' + message + '</p></div></div><br><br>');
$('.line').animate({ scrollTop: $('.line')[0].scrollHeight }, 'fast');
}
function appendMyMsg(message) {
$(".line").append('<div class="mycomment"><p>' + message + '</p></div><br>');
$('.line').animate({ scrollTop: $('.line')[0].scrollHeight }, 'fast');
}
function message() {
if ($("#msgForm").val() != '') {
var message = $("#msgForm").val();
appendMyMsg(message);
$("#msgForm").val('');
socket.emit("client_to_server", { message: message, name: name });
}
}
function joinUser(name) {
var selectRoom = 1;
socket.emit("client_to_server_join", { room: selectRoom, name: name });
}
$('#msgForm').keypress(function (e) {
if (e.which == 13 && $("#msgForm").val() != ' ') {
message();
return false;
}
});
chatServer.js
var http = require('http');
var socketio = require('socket.io');
var server = http.createServer(function (req, res) {
}).listen(3000);
var io = socketio.listen(server);
io.sockets.on('connection', function (socket) {
var room = '';
var name = '';
socket.on('client_to_server_join', function (data) {
room = data.room;
name = data.name;//名前追加
socket.join(room);
io.to(room).emit('server_to_client_join', { join: name + "さんが入室しました。" });//ルーム全体にブロードキャスト
});
socket.on('client_to_server', function (data) {
socket.broadcast.to(room).emit('server_to_client', { otherMsg: data.message, name: name });//名前も送信
});
socket.on('disconnect', function () {//接続切れ処理
if (name == '') {
console.log("未入室のまま、どこかへ去っていきました。");
} else {
io.to(room).emit('server_to_client_join', { join: name + "さんが退室しました。" });//ルーム全体にブロードキャスト
}
});
});
次回
次はアイコンをつけようと思います。
https://qiita.com/Catatataki/private/e9b71d1bbe5b7188751a