一、示例代码 封装类
<?php
namespace app\service;
use think\facade\Db;
/**
* 采集板
* Class TcpService
* @package app\service
*/
class TcpService
{
protected $http_url;
protected $host;
protected $port;
##自循环
protected $is_tcp;
/**
* 初始化
*/
public function __construct()
{
//域名
$this->host = env('tcp.hostname');
//端口
$this->port = env('tcp.port');
$this->http_url = 'http://'.env('tcp.hostname').':'.env('tcp.port').'/';
return $this;
}
//发送数据请求
public function sendPost(){
set_time_limit(0);
$ip = $this->host;
$port = $this->port;
//发送内容
$data = 'hello world';
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if($socket <0){
echo "socket创建失败:失败原因:".socket_strerror($socket)." ";exit;
}else{
echo "ok. ";
}
echo "试图连接'$ip'端口'$port'...";
$result = socket_connect($socket,$ip,$port);
if($result < 0){
echo 'socket连接失败:失败原因:'.socket_strerror($result)." ";exit;
}else{
echo "连接OK ";
}
$in = "Ho "."first blood ";
$out = '';
if(!socket_write($socket,$in,strlen($in))){
echo 'socket数据发送失败:原因是:'.socket_strerror($socket)." ";
}else{
echo "发送内容成功! ";
echo "发送的内容为:<font color='red'>$in</font><br>";
}
while($out == socket_read($socket, 8192)){
echo "接收服务器回传信息成功! ";
echo "接受的内容为:".$out;
break;
}
echo "关闭socket... ";
socket_close($socket);
echo "关闭ok ";
}
//接收数据
public function getReceive(){
$ip = $this->host;
$port = $this->port;
set_time_limit(0);
if(($sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP))<0){
echo 'socket_create()失败的原因是:'.socket_strerror($sock).' ';
}
if(($ret = socket_bind($sock,$ip,$port))<0){
echo 'socket_bind()失败的原因是:'.socket_strerror($ret).' ';
}
if(($lis = socket_listen($sock,4))<0){
echo 'socket_listen()失败的原因是:'.socket_strerror($lis).' ';
}
$count = 0;
do{
if(($msgsock = socket_accept($sock))<0){
echo "socket_accept() failed:reason:".socket_strerror($msgsock).' ';
break;
}else{
$msg = "测试成功! ";
socket_write($msgsock,$msg,strlen($msg));
echo "测试成功了啊 ";
$buf = socket_read($msgsock,8192);
$talkback = "收到的信息:$buf ";
echo $talkback;
if(++$count >= 5){
break;
};
}
socket_close($msgsock);
}while(true);
socket_close($sock);
}
}
二、总结
按照自己的逻辑写好都可以正常接入