1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
|
/** * patServer * PHP socket server base class * Events that can be handled: * * onStart * * onConnect * * onConnectionRefused * * onClose * * onShutdown * * onReceiveData * * @version 1.1 * @author Stephan Schmidt <schst@php-tools.de> * @package patServer */ class patServer { /** * information about the project * @var array $systemVars */ var $systemVars = array ( "appName" => "patServer" , "appVersion" => "1.1" , "author" => array ( "Stephan Schmidt <schst@php-tools.de>" , ) ); /** * port to listen * @var integer $port */ var $port = 10000; /** * domain to bind to * @var string $domain */ var $domain = "localhost" ; /** * maximum amount of clients * @var integer $maxClients */ var $maxClients = -1; /** * buffer size for socket_read * @var integer $readBufferSize */ var $readBufferSize = 128; /** * end character for socket_read * @var integer $readEndCharacter */ var $readEndCharacter = "\n" ; /** * maximum of backlog in queue * @var integer $maxQueue */ var $maxQueue = 500; /** * debug mode * @var boolean $debug */ var $debug = true; /** * debug mode * @var string $debugMode */ var $debugMode = "text" ; /** * debug destination (filename or stdout) * @var string $debugDest */ var $debugDest = "stdout" ; /** * empty array, used for socket_select * @var array $null */ var $null = array (); /** * all file descriptors are stored here * @var array $clientFD */ var $clientFD = array (); /** * needed to store client information * @var array $clientInfo */ var $clientInfo = array (); /** * needed to store server information * @var array $serverInfo */ var $serverInfo = array (); /** * amount of clients * @var integer $clients */ var $clients = 0; /** * create a new socket server * * @access public * @param string $domain domain to bind to * @param integer $port port to listen to */ function patServer( $domain = "localhost" , $port = 10000 ) { $this ->domain = $domain ; $this ->port = $port ; $this ->serverInfo[ "domain" ] = $domain ; $this ->serverInfo[ "port" ] = $port ; $this ->serverInfo[ "servername" ] = $this ->systemVars[ "appName" ]; $this ->serverInfo[ "serverversion" ] = $this ->systemVars[ "appVersion" ]; set_time_limit( 0 ); } /** * set maximum amount of simultaneous connections * * @access public * @param int $maxClients */ function setMaxClients( $maxClients ) { $this ->maxClients = $maxClients ; } /** * set debug mode * * @access public * @param mixed $debug [text|htmlfalse] * @param string $dest destination of debug message (stdout to output or filename if log should be written) */ function setDebugMode( $debug , $dest = "stdout" ) { if ( $debug === false ) { $this ->debug = false; return true; } $this ->debug = true; $this ->debugMode = $debug ; $this ->debugDest = $dest ; } /** * start the server * * @access public * @param int $maxClients */ function start() { $this ->initFD = @socket_create( AF_INET, SOCK_STREAM, 0 ); if ( ! $this ->initFD ) die ( "patServer: Could not create socket." ); // adress may be reused socket_setopt( $this ->initFD, SOL_SOCKET, SO_REUSEADDR, 1 ); // bind the socket if ( !@socket_bind( $this ->initFD, $this ->domain, $this ->port ) ) { @socket_close( $this ->initFD ); die ( "patServer: Could not bind socket to " . $this ->domain. " on port " . $this ->port. " ( " . $this ->getLastSocketError( $this ->initFd ). " )." ); } // listen on selected port if ( !@socket_listen( $this ->initFD, $this ->maxQueue ) ) die ( "patServer: Could not listen ( " . $this ->getLastSocketError( $this ->initFd ). " )." ); $this ->sendDebugMessage( "Listening on port " . $this ->port. ". Server started at " . date ( "H:i:s" , time() ) ); // this allows the shutdown function to check whether the server is already shut down $GLOBALS [ "_patServerStatus" ] = "running" ; // this ensures that the server will be sutdown correctly register_shutdown_function( array ( $this , "shutdown" ) ); if ( method_exists( $this , "onStart" ) ) $this ->onStart(); $this ->serverInfo[ "started" ] = time(); $this ->serverInfo[ "status" ] = "running" ; while ( true ) { $readFDs = array (); array_push ( $readFDs , $this ->initFD ); // fetch all clients that are awaiting connections for ( $i = 0; $i < count ( $this ->clientFD ); $i ++ ) if ( isset( $this ->clientFD[ $i ] ) ) array_push ( $readFDs , $this ->clientFD[ $i ] ); // block and wait for data or new connection $ready = @socket_select( $readFDs , $this ->null, $this ->null, NULL ); if ( $ready === false ) { $this ->sendDebugMessage( "socket_select failed." ); $this ->shutdown(); } // check for new connection if ( in_array( $this ->initFD, $readFDs ) ) { $newClient = $this ->acceptConnection( $this ->initFD ); // check for maximum amount of connections if ( $this ->maxClients > 0 ) { if ( $this ->clients > $this ->maxClients ) { $this ->sendDebugMessage( "Too many connections." ); if ( method_exists( $this , "onConnectionRefused" ) ) $this ->onConnectionRefused( $newClient ); $this ->closeConnection( $newClient ); } } if ( -- $ready <= 0 ) continue ; } // check all clients for incoming data for ( $i = 0; $i < count ( $this ->clientFD ); $i ++ ) { if ( !isset( $this ->clientFD[ $i ] ) ) continue ; if ( in_array( $this ->clientFD[ $i ], $readFDs ) ) { $data = $this ->readFromSocket( $i ); // empty data => connection was closed if ( ! $data ) { $this ->sendDebugMessage( "Connection closed by peer" ); $this ->closeConnection( $i ); } else { $this ->sendDebugMessage( "Received " .trim( $data ). " from " . $i ); if ( method_exists( $this , "onReceiveData" ) ) $this ->onReceiveData( $i , $data ); } } } } } /** * read from a socket * * @access private * @param integer $clientId internal id of the client to read from * @return string $data data that was read */ function readFromSocket( $clientId ) { // start with empty string $data = "" ; // read data from socket while ( $buf = socket_read( $this ->clientFD[ $clientId ], $this ->readBufferSize ) ) { $data .= $buf ; $endString = substr ( $buf , - strlen ( $this ->readEndCharacter ) ); if ( $endString == $this ->readEndCharacter ) break ; if ( $buf == NULL ) break ; } if ( $buf === false ) $this ->sendDebugMessage( "Could not read from client " . $clientId . " ( " . $this ->getLastSocketError( $this ->clientFD[ $clientId ] ). " )." ); return $data ; } /** * accept a new connection * * @access public * @param resource &$socket socket that received the new connection * @return int $clientID internal ID of the client */ function acceptConnection( & $socket ) { for ( $i = 0 ; $i <= count ( $this ->clientFD ); $i ++ ) { if ( !isset( $this ->clientFD[ $i ] ) || $this ->clientFD[ $i ] == NULL ) { $this ->clientFD[ $i ] = socket_accept( $socket ); socket_setopt( $this ->clientFD[ $i ], SOL_SOCKET, SO_REUSEADDR, 1 ); $peer_host = "" ; $peer_port = "" ; socket_getpeername( $this ->clientFD[ $i ], $peer_host , $peer_port ); $this ->clientInfo[ $i ] = array ( "host" => $peer_host , "port" => $peer_port , "connectOn" => time() ); $this ->clients++; $this ->sendDebugMessage( "New connection ( " . $i . " ) from " . $peer_host . " on port " . $peer_port ); if ( method_exists( $this , "onConnect" ) ) $this ->onConnect( $i ); return $i ; } } } /** * check, whether a client is still connected * * @access public * @param integer $id client id * @return boolean $connected true if client is connected, false otherwise */ function isConnected( $id ) { if ( !isset( $this ->clientFD[ $id ] ) ) return false; return true; } /** * close connection to a client * * @access public * @param int $clientID internal ID of the client */ function closeConnection( $id ) { if ( !isset( $this ->clientFD[ $id ] ) ) return false; if ( method_exists( $this , "onClose" ) ) $this ->onClose( $id ); $this ->sendDebugMessage( "Closed connection ( " . $id . " ) from " . $this ->clientInfo[ $id ][ "host" ]. " on port " . $this ->clientInfo[ $id ][ "port" ] ); @socket_close( $this ->clientFD[ $id ] ); $this ->clientFD[ $id ] = NULL; unset( $this ->clientInfo[ $id ] ); $this ->clients--; } /** * shutdown server * * @access public */ function shutDown() { if ( $GLOBALS [ "_patServerStatus" ] != "running" ) exit ; $GLOBALS [ "_patServerStatus" ] = "stopped" ; if ( method_exists( $this , "onShutdown" ) ) $this ->onShutdown(); $maxFD = count ( $this ->clientFD ); for ( $i = 0; $i < $maxFD ; $i ++ ) $this ->closeConnection( $i ); @socket_close( $this ->initFD ); $this ->sendDebugMessage( "Shutdown server." ); exit ; } /** * get current amount of clients * * @access public * @return int $clients amount of clients */ function getClients() { return $this ->clients; } /** * send data to a client * * @access public * @param int $clientId ID of the client * @param string $data data to send * @param boolean $debugData flag to indicate whether data that is written to socket should also be sent as debug message */ function sendData( $clientId , $data , $debugData = true ) { if ( !isset( $this ->clientFD[ $clientId ] ) || $this ->clientFD[ $clientId ] == NULL ) return false; if ( $debugData ) $this ->sendDebugMessage( "sending: \"" . $data . "\" to: $clientId" ); if ( !@socket_write( $this ->clientFD[ $clientId ], $data ) ) $this ->sendDebugMessage( "Could not write '" . $data . "' client " . $clientId . " ( " . $this ->getLastSocketError( $this ->clientFD[ $clientId ] ). " )." ); } /** * send data to all clients * * @access public * @param string $data data to send * @param array $exclude client ids to exclude */ function broadcastData( $data , $exclude = array (), $debugData = true ) { if ( ! empty ( $exclude ) && ! is_array ( $exclude ) ) $exclude = array ( $exclude ); for ( $i = 0; $i < count ( $this ->clientFD ); $i ++ ) { if ( isset( $this ->clientFD[ $i ] ) && $this ->clientFD[ $i ] != NULL && !in_array( $i , $exclude ) ) { if ( $debugData ) $this ->sendDebugMessage( "sending: \"" . $data . "\" to: $i" ); if ( !@socket_write( $this ->clientFD[ $i ], $data ) ) $this ->sendDebugMessage( "Could not write '" . $data . "' client " . $i . " ( " . $this ->getLastSocketError( $this ->clientFD[ $i ] ). " )." ); } } } /** * get current information about a client * * @access public * @param int $clientId ID of the client * @return array $info information about the client */ function getClientInfo( $clientId ) { if ( !isset( $this ->clientFD[ $clientId ] ) || $this ->clientFD[ $clientId ] == NULL ) return false; return $this ->clientInfo[ $clientId ]; } /** * send a debug message * * @access private * @param string $msg message to debug */ function sendDebugMessage( $msg ) { if ( ! $this ->debug ) return false; $msg = date ( "Y-m-d H:i:s" , time() ) . " " . $msg ; switch ( $this ->debugMode ) { case "text" : $msg = $msg . "\n" ; break ; case "html" : $msg = htmlspecialchars( $msg ) . "<br />\n" ; break ; } if ( $this ->debugDest == "stdout" || empty ( $this ->debugDest ) ) { echo $msg ; flush (); return true; } error_log ( $msg , 3, $this ->debugDest ); return true; } /** * return string for last socket error * * @access public * @return string $error last error */ function getLastSocketError( & $fd ) { $lastError = socket_last_error( $fd ); return "msg: " . socket_strerror( $lastError ) . " / Code: " . $lastError ; } function onReceiveData( $ip , $data ){ $this ->broadcastData( $data , array (), true ); } } $patServer = new patServer(); $patServer ->start(); |
php socket实现的聊天室代码分享
2020-07-22 15:42PHP教程网 PHP教程
这篇文章主要介绍了php socket实现的聊天室代码分享,本文实现代码来自国外友人,需要的朋友可以参考下
延伸 · 阅读
- 2022-03-10简单谈谈centos7中配置php
- 2022-03-09C#学习教程之Socket的简单使用
- 2022-03-08Linux下Select多路复用实现简易聊天室示例
- 2022-03-08深入讲解Socket原理
- 2022-03-06Ubuntu14.04服务器环境下配置PHP7.0+Apache2+Mysql5.7的方
- 2022-03-05centos yum php 7.x 无需删除升级的方法
- PHP教程
PHP变量的定义、可变变量、变量引用、销毁方法
这篇文章主要介绍了PHP变量的定义、可变变量、变量引用、销毁方法,需要的朋友可以参考下 ...
- PHP教程
php学习笔记 数组的常用函数
只要一个变量,需要在多个方法使用,就将这个变量声明为成员属性,可以直接在这个对象中的所有方法中使用 成员属性,相当于这个对象中的全局变量...
- PHP教程
php htmlentities()函数的定义和用法
下面小编就为大家带来一篇php htmlentities()函数的定义和用法。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...
- PHP教程
php全角字符转换为半角函数
这篇文章主要介绍了PHP全角半角转换函数,把目前能找到的所有全角都列出来了一个个替换吧,需要的朋友可以参考下 ...
- PHP教程
php实现的支持imagemagick及gd库两种处理的缩略图生成类
这篇文章主要介绍了php实现的支持imagemagick及gd库两种处理的缩略图生成类,包含了用法的详细描述,非常实用,需要的朋友可以参考下...
- PHP教程
php学习之数据类型之间的转换介绍
php学习之数据类型之间的转换介绍,学习php的朋友可以参考下。 ...
- PHP教程
PHP常量DIRECTORY_SEPARATOR原理及用法解析
这篇文章主要介绍了PHP常量DIRECTORY_SEPARATOR原理及用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友...
- PHP教程
PHP中读取文件的8种方法和代码实例
这篇文章主要介绍了PHP中读取文件的8种方法和代码实例,本文总结了PHP中读取文件的8个函数,每一个都附有使用例子及注意事项等,需要的朋友可以参考下...