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 οnclick="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++模块。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值