-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSocketClient.php
84 lines (74 loc) · 1.65 KB
/
SocketClient.php
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
<?php
/**
* @author Ewan
* @email [email protected]
* The more effort ,the more lucky
* .--.
* |o_o |
* |:_/ |
* // \ \
* (| | )
* /'\_ _/`\
* \___)=(___/
* @time: 16/12/19 上午9:44
*/
namespace Socket;
class SocketClient extends Socket
{
/**
* 超时前多少毫秒
*
* @var integer
*/
protected $timeout_milliseconds = 0;
/**
* 超时钱多少秒
*
* @var integer
*/
protected $timeout_seconds = 10;
/**
* 构造函数
*
* @param string $host 类似localhost,127.0.0.1或者其它IP
* @param integer $port 8080或者其它不被占用的端口
*/
public function __construct($host, $port)
{
$this->create($host, $port);
$this->connect();
}
/**
* 写入服务器
*
* @param string $str
* @return integer
*/
public function write($str)
{
// 写入到Socket,发送至服务器
parent::write($this->socket, $str);
}
/**
* 读取服务器响应
*
* @return string
*/
public function read()
{
return $this->_read($this->socket);
}
/**
* 连接Socket
*/
protected function connect()
{
// 设置socket参数...
$timeout = array('sec' => $this->timeout_seconds, 'usec' => $this->timeout_milliseconds);
socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, $timeout);
if (!@socket_connect($this->socket, $this->host, $this->port)) {
$this->throwError(sprintf('Could not connect to %s:%s', $this->host, $this->port));
}
return true;
}
}