一些關於搭建服務器的方法


搭建node.js 去node官網下載安裝環境。

# 安裝nodejs


```
node --version
v10.15.1

npm --version
6.4.1
```


# 生成配置文件


```
回到自己的項目目錄里面
cd E:\phpStudy\WWW\h1901\0521\game

npm init 執行該命令會生成一個package.json文件
```


安裝socket.io 插件

```

安裝插件,並寫到配置文件里面去
npm install socket.io --save
npm install websocket.io --save

框架
npm install express --save
```
然后直到在自己本地服務器上面顯示下面圖上兩個文件夾

 

一、我們建立一個登錄 界面里面也有相關聯的js。代碼如下:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7     <title>登錄頁面</title>
 8     <style>
 9         *{
10             padding: 0;
11             margin: 0;
12         }
13         .box{
14             padding-top: 100px;
15             margin: auto;
16         }
17         h1{
18             text-align: center;
19             font-weight: normal;
20         }
21         p{
22             margin: auto;
23             text-align: center;
24             margin: 20px 0px;
25         }
26         p input{
27             width: 230px;
28             height: 35px;
29             margin: auto;
30             text-align: center;
31         }
32         button{
33             width: 230px;
34             height: 45px;
35             margin: auto;
36             background: skyblue;
37             color: white;
38             line-height: 45px;
39             display: block;
40             border-radius: 5px;
41         }
42     </style>
43 </head>
44 <body>
45     <div class="box">
46       <form id="login"> 
47             <h1>登錄界面</h1>
48         <p><input type="text" name="username" class="username" id="username" placeholder="用戶名" required /></p>
49         <button class="btn">登錄</button>
50       </form>
51     </div>
52 </body>
53 </html>
54 <script src="./socket.io.js"></script>
55 <script src="./jquery-1.7.2.min.js"></script>
56 <script>
57   
58   var ws = io.connect("http://localhost:3000");
59    //接收服務器的結果 是主動的
60 
61    ws.on("clientUser",function(obj){
62        if(obj.res)
63        {
64            alert(`${obj.msg}已經存在了,請重新輸入`);
65            $("#username").val("");
66            $("#username").focus();
67            return false;
68        }else{
69            //跳轉默然首頁
70            console.log('用戶已經注冊');
71        }
72 
73    });
74 
75    $("#login").submit(function(){
76         var username = $.trim($("#username").val());
77 
78         if(!username)
79         {
80             alert('昵稱不能為空,請重新輸入');
81             return false;
82         }else{
83             //執行所連接服務器上面的方法
84             ws.emit('join',username);
85         }
86 
87 
88 
89         return false;
90    });
91 </script>

 

 

二、我們使用的是Node.js,自己封裝一個函數判斷登錄用戶是否符合我們的檢測。代碼如下;

 

 1 //服務器端 nodejs充當服務器
 2 var express= require('express'),
 3     io = require('socket.io');
 4 
 5 
 6 //創建一個應用
 7 var app = express();
 8 
 9 //綁定應用的監聽端口
10 var server = app.listen(3000,function(){
11     console.log('服務已開啟');
12 });
13 
14 
15 //用socket來監聽服務
16 var ws = io.listen(server);
17 
18 
19 //給監聽綁定動作
20 
21 //新建方法 檢測用戶是否存在
22 var checkUser = function(username)
23 {
24     //ws.sockets.sockets 該對象里面放的是所有連接的客戶端對象
25     for(var key in ws.sockets.sockets)
26     {
27         if(ws.sockets.sockets[key].username == username)
28         {
29             return true;  //用戶存在
30         }
31     }
32     return false; //用戶不存在
33 }
34 
35 //connection 連接事件 客戶端連接到服務器 就會觸發
36 //client 客戶端對象
37 ws.on("connection",function(client){
38     console.log('客戶端已經連接到服務器');
39 
40     //給客戶端弄一個接收數據的一個方法
41     client.on('join',function(username){
42 
43         if(checkUser(username))
44         {
45             //說明存在了 調用會客戶端
46             client.emit('clientUser',{res:true,msg:username});
47         }else{
48             //走進else說明這個人不存在,保存 
49             //自定義對象屬性
50             client.username = username;
51             console.log('該用戶不存在');
52             client.emit('clientUser',{res:false,msg:username});
53         }
54         
55     });
56 })

 

})

三、我們這里也還要引進一個php文件,代碼如下:

  1 <?php 
  2 
  3 /**
  4 * 聊天室服務器  websocket 專用
  5 */
  6 class Server_socket
  7 {
  8     private $socket;
  9     private $accept = [];
 10     private $hands = [];
 11     function __construct($host, $port, $max)
 12     {
 13         //創建一個socket連接,並且設置端口和地址,最大連接數
 14         $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
 15         socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, TRUE);
 16         socket_bind($this->socket, $host,$port);
 17         socket_listen($this->socket,$max); 
 18         print_r($this->socket);
 19     }
 20 
 21     public function start()
 22     {
 23         $i = 0;
 24         while (true) {
 25 
 26             $cycle = $this->accept;
 27             $cycle[] = $this->socket;
 28             socket_select($cycle, $write, $except, null);
 29 
 30             foreach ($cycle as $sock) {
 31                 if ($sock == $this->socket) {
 32                     $this->accept[] = socket_accept($sock);
 33                     $arr =  array_keys($this->accept);
 34                     $key = end($arr);
 35                     $this->hands[$key] = false;
 36                 }else{
 37                     $length = socket_recv($sock, $buffer, 204800, null);
 38                     $key = array_search($sock, $this->accept);
 39                     if (!$this->hands[$key]) {
 40                         $this->dohandshake($sock,$buffer,$key);
 41                     }else if($length < 1){
 42                         $this->close($sock);
 43                     }else{
 44                         //接收從客戶端發送的內容 解碼
 45                         $data = $this->decode($buffer);
 46                         print_r("\nThis is the data received from client,".$data);
 47                         //服務器端的內容  編碼
 48                         //$data = "This is the data sent by server".$i.", so smart";
 49                         $data = $this->encode($data);
 50                         print_r($data);
 51                         //將信息傳遞給從機
 52                         foreach ($this->accept as $client) {
 53                             socket_write($client,$data ,strlen($data));
 54                         }
 55                         $i++;    
 56                     }         
 57                 }
 58             }
 59             sleep(1);
 60         }
 61     }/* end of start*/
 62 
 63     /**
 64      * 首次與客戶端握手
 65      */
 66     public function dohandshake($sock, $data, $key) {
 67         if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $data, $match)) {
 68             $response = base64_encode(sha1($match[1] . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
 69             $upgrade  = "HTTP/1.1 101 Switching Protocol\r\n" .
 70                     "Upgrade: websocket\r\n" .
 71                     "Connection: Upgrade\r\n" .
 72                     "Sec-WebSocket-Accept: " . $response . "\r\n\r\n";
 73             socket_write($sock, $upgrade, strlen($upgrade));
 74             $this->hands[$key] = true;
 75         }
 76     }/*dohandshake*/
 77 
 78     /**
 79      * 關閉一個客戶端連接
 80      */
 81     public function close($sock) {
 82         $key = array_search($sock, $this->accept);
 83         socket_close($sock);
 84         unset($this->accept[$key]);
 85         unset($this->hands[$key]);
 86     }
 87 
 88     /**
 89      * 字符解碼
 90      */
 91     public function decode($buffer) {
 92         $len = $masks = $data = $decoded = null;
 93         $len = ord($buffer[1]) & 127;
 94         if ($len === 126) {
 95             $masks = substr($buffer, 4, 4);
 96             $data = substr($buffer, 8);
 97         } 
 98         else if ($len === 127) {
 99             $masks = substr($buffer, 10, 4);
100             $data = substr($buffer, 14);
101         } 
102         else {
103             $masks = substr($buffer, 2, 4);
104             $data = substr($buffer, 6);
105         }
106         for ($index = 0; $index < strlen($data); $index++) {
107             $decoded .= $data[$index] ^ $masks[$index % 4];
108         }
109         return $decoded;
110     }
111 
112     /**
113      * 字符編碼
114      */
115     public function encode($buffer) {
116         $length = strlen($buffer);
117         if($length <= 125) {
118             return "\x81".chr($length).$buffer;
119         } else if($length <= 65535) {
120             return "\x81".chr(126).pack("n", $length).$buffer;
121         } else {
122             return "\x81".char(127).pack("xxxxN", $length).$buffer;
123         }
124     }
125 
126 }/* end of class Server_socket*/
127 
128 
129 
130 // 在執行該腳本的時候一定要注意是服務器要開啟對應環境擴展
131 // php開啟這個擴展  php_sockets
132 
133 //要用命令行  php
134 //
135 
136 // cd E:\phpStudy\php\php-5.5.38\
137 // E:
138 // php.exe E:\phpStudy\WWW\h1901\0521\game\server.php
139 
140 //實例化
141 $server_socket = new Server_socket('127.0.0.1',9000,20);
142 $server_socket->start(); sleep(2); 
143 ?>

 

四、實現效果如下:

1、

2、

具體開啟node.js 服務器的關機鍵步驟:

①要在本地電腦服務器上的相對文件路徑,因為我這里本地用的是phpStudy,所以如果不一樣的話還要找其他參考方法

②:然后到命令符界面開啟我們自己搭建的服務器,如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM