首頁 >後端開發 >php教程 >php之socket網路操作類

php之socket網路操作類

不言
不言原創
2018-04-26 14:40:011290瀏覽

這次的這篇文章跟大家分享了關於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 = &#39;192.168.238.1&#39;;
			$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(&#39;mysocket.php&#39;); 

$con = Connector::getInstance();
$req = $_GET[&#39;cmd&#39;];
$con->sendMsg($req);
$ret = $con->getMsg();
echo $ret;
?>

## 應用說明


客戶端ajax發起請求呼叫Php,然後php借助socket進一步發起請求給C++模組。

相關推薦:

PHP之SOCKET程式設計詳

#MAC上php中websocket的連線設定


################################# #####php中socket通訊詳解###############

以上是php之socket網路操作類的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn