socket.io 入門篇(二)

本文原文地址:https://www.limitcode.com/detail/5922f1ccb1d4fe074099d9cd.html

前言

上篇咱們介紹了 socket.io 基本使用方法,本篇咱們繼續深刻了解 socket.io 中 room(房間)的概念和使用。javascript

對於 room 的概念,你只需理解3個地方就能夠:html

1. 在不加入或指定room的狀況下,socket.io 會默認分配一個default roomjava

2. 同一room下的socket能夠廣播消息express

3. join(房間名) 加入一個房間;leave(房間名) 離開一個房間;broadcast.to(房間名).emit() 給同一個房間的其餘socket廣播消息json

源碼下載地址:http://pan.baidu.com/s/1eSaf1Pgapp

項目文件結構

服務端

/**
 * Created by mike on 2017/5/15.
 */

var http=require("http");
var express=require("express");//引入express
var socketIo=require("socket.io");//引入socket.io

var app=new express();

var server=http.createServer(app);
var io=new socketIo(server);//將socket.io注入express模塊

//客戶端 1 的訪問地址
app.get("/client1",function (req,res,next) {
    res.sendFile(__dirname+"/views/client1.html");
});
app.get("/client2",function (req,res,next) {
    res.sendFile(__dirname+"/views/client2.html");
});
server.listen(8080);//express 監聽 8080 端口,由於本機80端口已被暫用
console.log("服務已啓動");

//每一個客戶端socket鏈接時都會觸發 connection 事件
io.on("connection",function (clientSocket) {
    // socket.io 使用 emit(eventname,data) 發送消息,使用on(eventname,callback)監聽消息

    //加入房間
    clientSocket.on("joinRoom",function (data,fn) {
        clientSocket.join(data.roomName); // join(房間名)加入房間
        fn({"code":0,"msg":"加入房間成功","roomName":data.roomName});
    });
    //退出 離開房間
    clientSocket.on("leaveRoom",function (data,fn) {
        clientSocket.leave(data.roomName);//leave(房間名) 離開房間
        fn({"code":0,"msg":"已退出房間","roomName":data.roomName});
    });
    //監聽客戶端發送的 sendMsg 事件
    clientSocket.on("sendMsg",function (data,fn) {
        // data 爲客戶端發送的消息,能夠是 字符串,json對象或buffer

        // 使用 emit 發送消息,broadcast 表示 除本身之外的全部已鏈接的socket客戶端。
        // to(房間名)表示給除本身之外的同一房間內的socket用戶推送消息
        clientSocket.broadcast.to(data.roomName).emit("receiveMsg",data);
        fn({"code":0,"msg":"消息發生成功"});
    })
});

 

客戶端(2個客戶端頁面內容同樣)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>客戶端1</title>
</head>
<body>

<label>房間名:</label>
<input type="text" id="txtRoom"/>
<button type="button" id="btn-joinRoom">加入房間</button>
<button type="button" id="btn-leaveRoom">離開房間</button>
<br/>

<label>聊天內容:</label><br/>
<textarea id="content" style="height: 200px; width:300px;"></textarea>
<br/>
<input  id="sendMsg" type="text"/>
<button id="btn_send">發送</button>

<!-- 首先引入 socket.io 客戶端腳本-->
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
 var socket = io.connect();//鏈接服務端,由於本機使用localhost 因此connect(url)中url能夠不填或寫 http://localhost
    // 監聽 receiveMsg 事件,用來接收其餘客戶端推送的消息
 socket.on("receiveMsg",function (data) {
        content.value+=data.client+":"+data.msg+"\r\n";
 });
 var content=document.getElementById("content");
 var sendMsg=document.getElementById("sendMsg");
 var btn_send=document.getElementById("btn_send");
 var btn_joinRoom=document.getElementById("btn-joinRoom");
 var btn_leaveRoom=document.getElementById("btn-leaveRoom");
 var txtRoom=document.getElementById("txtRoom");

 btn_leaveRoom.addEventListener("click",function () {
        socket.emit("leaveRoom",{"roomName":txtRoom.value},function (data) {
            //打印離開房間後服務端返回的信息
 console.log("離開房間:"+ JSON.stringify(data) )
        });
 txtRoom.value="";
 })
    btn_joinRoom.addEventListener("click",function () {
        var roomName=txtRoom.value;
 socket.emit("joinRoom",{"roomName":roomName},function (data) {
            //打印加入房間成功後返回的信息
 console.log("加入房間:"+JSON.stringify(data));
 })
    });
 btn_send.addEventListener("click",function () {
        if(!sendMsg.value){
            alert("請輸入房間號");return;
 }
        var data={"msg":sendMsg.value,"roomName":txtRoom.value,"client":"客戶端1"};
 //給服務端發送 sendMsg事件名的消息
 socket.emit("sendMsg",data,function (data) {
            //打印消息發送成功後服務端返回的信息
 console.log("消息發送:"+JSON.stringify(data));
 });
 content.value+=data.client+":"+data.msg+"\r\n";
 sendMsg.value="";
 });

    

</script>

</body>
</html>

 

界面效果以下:socket

相關文章
相關標籤/搜索