这次的这篇文章给大家分享了关于php中的socket网络操作类的代码,有兴趣的朋友可以看一下这篇文章的内容
## web前端测试
<html>
<head>
<title>test</title>
<script>
g_xmlhttpreq = new xmlhttprequest();
function onreplycallback()
{
if(g_xmlhttpreq.readystate==4 && g_xmlhttpreq.status==200)
{
alert(g_xmlhttpreq.responsetext);
}
}
function on_stop_service()
{
var cmd = document.getelementbyid("incmd").value;
g_xmlhttpreq.open("get","./service/main.php?cmd=" + cmd,true);
g_xmlhttpreq.onreadystatechange=onreplycallback;
g_xmlhttpreq.send(null);
}
</script>
</head>
<body>
<input type="text" id="incmd">
<hr>
<button onclick="on_stop_service()">关闭服务</button>
</body>
</html>
## mysocket.php
<?php
class connector
{
public static $instance=null;
public $conn;
private function __construct()
{
set_time_limit(0);
$ip = '192.168.238.1';
$port = 8888;
if(($this->conn = socket_create(af_inet,sock_stream,sol_tcp)) < 0)
{
echo "socket_create() 失败的原因是:".socket_strerror($this->conn)."\n";
}
$result = socket_connect($this->conn, $ip, $port);
if ($result < 0) {
echo "socket_connect() failed.\nreason: ($result) " . socket_strerror($result) . "\n";
}else {
echo "连接ok\n";
}
}
public static function getinstance()
{
if(is_null(self::$instance))
{
self::$instance = new connector;
}
return self::$instance;
}
public function sendmsg($msg)
{
socket_write($this->conn,$msg);
}
public function getmsg()
{
$clients = array($this->conn);
while(true)
{
$read = $clients;
$wrset = null;
$errset = null;
if(socket_select($read, $wrset,$errset, 3) < 1)
{
continue;
}
foreach($read as $read_sock)
{
$data = @socket_read($read_sock,1024,php_binary_read);
socket_close($this->conn);
return $data;
}
}
}
}
?>
## main.php(调用场所)
<?php
require_once('mysocket.php');
$con = connector::getinstance();
$req = $_get['cmd'];
$con->sendmsg($req);
$ret = $con->getmsg();
echo $ret;
?>
## 应用说明
客户端ajax发起请求调用php,然后php借助socket进一步发起请求给c++模块。
相关推荐:
php之socket编程详解
mac上php中websocket的连接设置
php中socket通讯详解
以上就是php之socket网络操作类 的详细内容。