使用socket.io怎么編寫一個WEB聊天室?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
1. 創建一個空的工程目錄
空的目錄命名為chat-web
2. 創建package.json
使用命令:npm init,會引導你設置package.json的內容.
3.安裝依賴包
使用命令:
npm install --save express npm install --save socket.io
安裝完成后你會在工程目錄看見有自動生成的node_modules文件夾
4.編寫index.js腳本
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
console.log("dir:" + __dirname);
res.sendFile( __dirname + '/index.html');
});
//所有注冊用戶的socket集合(socketMap)
var sm = {};
io.on('connection', function(socket){
socket.on('chat-reg',function(data){
console.log("chat-reg:" + JSON.stringify(data));
//注冊 :data 格式:{user:"alisa"}
//消息 :data 格式:{user:"alisa",msg:"@someone hello!!!"}
//格式說明:msg內容以@符號開頭,以空格分隔用戶名和消息體的說明是私聊
sm[data.user] = socket;
socket.emit('chat-reg',{code:200,msg:"reg success"});
});
socket.on('chat-data',function(data){
console.log("chat-data:" + JSON.stringify(data));
if(data.msg[0] == '@'){//以@符號開頭,說明這句消息是私聊
//將消息顯示在自己的聊天記錄上
socket.emit('chat-data',data);
//查找第一個空格的位置
var i = data.msg.indexOf(' ');
//得到用戶名
var u = data.msg.substring(1,i);
//得到消息體
var m = data.msg.substring(i,data.msg.length);
if(typeof sm[u] != 'undefined'){
//在socket集合中得到目標用戶的socket,并且發送消息事件
sm[u].emit('chat-data',{user:data.user,msg:"[private]" + m});
}
}else{
//不是以@開頭的消息發送給所有連接的用戶
io.sockets.emit('chat-data',data);
}
});
});
//監聽在3000端口
http.listen(3000, function(){
console.log('listening on:3000');
});5.寫index.html
<!doctype html>
<html>
<head>
<title>私人聊天室</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
#info{
height: 50px;
text-align: center;
line-height: 50px;
background-color: #333;
color: white;
}
</style>
</head>
<body>
<div id="info"></div>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="http://cdn.bootcss.com/socket.io/1.7.1/socket.io.min.js"></script>
<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script>
//頁面加載的時候隨機生成一個用戶名
var user = "user" + Math.floor(Math.random()*1000);
//打開一個socket,io()方法可以有namespace參數,默認為`/`,具體用法見官方
var socket = io();
//發送一個用戶注冊事件,在服務器端注冊用戶名
socket.emit('chat-reg',{user:user});
//將用戶名顯示在信息欄
$("#info").text("您的用戶名:"+user);
$('form').submit(function(){
//發送聊天信息
socket.emit('chat-data', {user:user,msg:$('#m').val()});
$('#m').val('');
return false;
});
//監聽服務端發送的聊天信息,并將其顯示在頁面中
socket.on('chat-data', function(data){
$('#messages').append($('<li>').text("[" + data.user + "]:" + data.msg));
});
//注冊成功后,在控制臺顯示返回的信息
socket.on('chat-reg',function(data){
console.log(JSON.stringify(data));
});
</script>
</body>
</html>關于使用socket.io怎么編寫一個WEB聊天室問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。