單個聊天室的專案
Nodejs server side
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/views/chatroom.html');
});
var user_count = 0;
io.on('connection', function(socket){
socket.on('add_user',function(msg){
socket.username = msg;
console.log("new user:"+msg+" logged.");
io.emit('add_user',{
username: socket.username
});
});
socket.on('chat_message', function(msg){
console.log(socket.username+":"+msg);
io.emit('chat_message', {
username:socket.username,
msg:msg
});
});
socket.on('disconnect',function(){
console.log(socket.username+" left.");
io.emit('user_left',{
username:socket.username
});
});
});
http.listen(3000, function() {
console.log("伺服器跑起來啦!");
console.log("在你的瀏覽器網址列輸入 localhost:"+3000+" 吧!");
});
HTML client side
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font: 13px Helvetica, Arial;
}
#m {
padding: 10px;
width: 90%;
margin: .5%;
position: fixed;
bottom: 0;
}
#sticker {
width: 50px;
margin: .5%;
padding: 10px;
position: fixed;
bottom: 50px;
right: 5px;
z-index: 1;
}
#send {
width: 8%;
margin: .5%;
padding: 10px;
position: fixed;
bottom: 0;
right: 5px;
}
#message-block {
width: 100%;
position: absolute;
top: 0;
bottom: 5%;
margin-bottom: 10px;
overflow: auto;
}
#messages {
list-style-type: none;
margin: 10px;
padding: 0;
}
#messages li {
padding: 5px 10px;
font-size: 16pt;
}
#messages li:nth-child(odd) {
background: #eee;
}
</style>
<script>
var socket = io();
$(document).ready(function () {
var name = prompt("請輸入暱稱", "訪客" + Math.floor(Math.random() * 100));
if (name == "" || name == null) {
name = "無名的旅人";
}
socket.emit("add_user", name);
socket.on('chat_message', function (data) {
appendMessage(data.username + ":" + data.msg);
});
socket.on('add_user', function (data) {
appendMessage(data.username + " 已加入");
});
socket.on('user_left', function (data) {
appendMessage(data.username + " 已離開");
});
$('#send').click(sendMessage);
$("#m").keydown(keyDown);
});
function keyDown(event) {
if (event.which == 13) {
$('#send').click();
}
}
function sendMessage() {
var text = $('#m').val();
if (text == "") {
return false;
}
socket.emit('chat_message', text);
$('#m').val('');
return false;
}
function appendMessage(msg) {
$('#messages').append($('<li>').text(msg));
var message = document.getElementById("message-block");
message.scrollTop = message.scrollHeight;
}
</script>
</head>
<body>
<div id="message-block">
<ul id="messages"></ul>
<div>
<input id="m" autocomplete="off" />
<button id="send">傳送</button>
</body>
</html>