套接字连接,的应用实例分析

by admin on 2019年8月1日

    今日试着写三个 PHP 与 C
语言因而socket通讯的先后,看过PHP手册,开采有几许种艺术得以创立socket
客户端.

理之当然是搜一些html5
websocket资料看的,结果被引去看了php的socket编制程序。上面是一对简约的例证,在命令行运营php脚本就行

fsockopen函数能够使用,首先要开启php.ini中的allow_url_open=on;
fsockopen是对socket客户端代码的包裹,该函数中封装了socket_create,socket_connect。
劳务器端代码:server.php

PHP socket增添是基于流行的BSD
sockets,实现了和socket通信功用的平底接口,它能够和客户端同样当做八个socket服务器。

1、通过 fsockopen() 建立socket连接,然后用 用fputs() 发送音讯,用
fgets() 接收新闻。

[命令行运维PHP]PHP中有一个php.exe文件,可以用命令实施PHP脚本。如:D:/php.exe
-f F:/test.php ; 能够应用php.exe -h查看越来越多参数 :

复制代码 代码如下:

选用这几个函数时请小心,就算他们中有相当多和C函数同名的,但扬言并非常的大概两样。未幸免混淆,请留心阅读函数描述。

2、通过 socket_套接字连接,的应用实例分析。create() 建立 socket 连接,然后用 socket_send() or
socket_write() 发送音信,用 socket_recv() or socket_read() 发送音讯。

 

<?php
error_reporting(E_ALL);
set_time_limit(0);
$address = ‘127.0.0.1’;
$port = 10008;
//制造端口
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) ===
false) {
echo “socket_create() failed:reason:” .
socket_strerror(socket_last_error()) . “\n”;
}
//绑定
if (socket_bind($sock, $address, $port) === false) {
echo “socket_bind() failed :reason:” .
socket_strerror(socket_last_error($sock)) . “\n”;
}
//监听
if (socket_listen($sock, 5) === false) {
echo “socket_bind() failed :reason:” .
socket_strerror(socket_last_error($sock)) . “\n”;
}
while (true) {
//获得多个链接
if (($msgsock = socket_accept($sock)) === false) {
echo “socket_accepty() failed
:reason:”.socket_strerror(socket_last_error($sock)) . “\n”;
break;
}
//welcome 发送到客户端
$msg = “1.<font color=’red’>server
send:welcome</font><br/>”;
socket_write($msgsock, $msg, strlen($msg)); //重回新闻给客户端
echo ‘read client message\n’;
$buf = socket_read($msgsock, 8192); //获取客户端发送过来的音信
$talkback = “2.received message:$buf\n”;
echo $talkback;
if (false === socket_write($msgsock, $talkback, strlen($talkback))) {
//重回音信给客户端
echo “socket_write() failed reason:” .
socket_strerror(socket_last_error($sock)) .”\n”;
} else {
echo ‘send success’;
}
socket_close($msgsock);
}
socket_close($sock);

不熟谙socket编制程序的能够在Unix手册上找到相当多实惠的信息,英特网也是有非常多C
socket编程方面包车型客车科目,轻松修改一下就可以动用于PHP socket编程。

套接字连接,的应用实例分析。   
很想得到,作者在手册上看到了如此一段话”本扩大模块是实验性的。该模块的作为,包罗其函数的名号以及其余任何关于此模块的文档或者会在尚未打招呼的场地下随
PHP 今后的颁发而改动。我们提示您在利用本扩展模块的还要自担危机。” 看来
php4.0 socket通信还不是完全稳固。

server端:

客户端代码:fsocket.php

第一步:开启socket

前天本身写的客户端要与服务端做四回通信,小编用地点这一个点子都写了三个客户端程序,开采当独有就二回通信的时候,相当于PHP客户端发送二次新闻,然后接收重回新闻,就破产连接。那三种格局都能科学火速的实现效果与利益,但作为三遍通信时,却有众人周知的差别,第一种办法第叁遍通讯相当的慢就截止了,那一个自家得以因此服务端的出口看出来,然而第贰遍通信要等上一些分钟才干终止,笔者试了一些次都如此,小编不太驾驭自个儿的顺序何地出错了,依旧那么些方法连接正是有标题,然则第三种办法做那五遍通信却飞速,正确!完结的特别的。

<?php /** * 服务器端代码 * */ //确认保障在连接客户端时不会晚点
set_time_limit(0); //设置IP和端口号 $address = “localhost”; $port =
1234; //调节和测验的时候,可以多换端口来测量试验程序! //成立一个SOCKET if (($sock
= socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) { echo
“socket_create() 退步的缘故是:” .
socket_strerror(socket_last_error()) . “/n”; die; } //阻塞情势 if
(socket_set_block($sock) == false) { echo “socket_set_block()
战败的来由是:” . socket_strerror(socket_last_error()) . “/n”; die; }
//绑定到socket端口 if (socket_bind($sock, $address, $port) == false) {
echo “socket_bind() 失利的案由是:” .
socket_strerror(socket_last_error()) . “/n”; die; } //开始监听 if
(socket_listen($sock, 4) == false) { echo “socket_listen()
失利的缘由是:” . socket_strerror(socket_last_error()) . “/n”; die; }
do { if (($msgsock = socket_accept($sock)) === false) { echo
“socket_accept() failed: reason: ” .
socket_strerror(socket_last_error()) . “/n”; die; } //发到客户端 $msg
= “welcome /n”; if (socket_write($msgsock, $msg, strlen($msg)) ===
false) { echo “socket_write() failed: reason: ” .
socket_strerror(socket_last_error()) .”/n”; die; } echo
“读取客户端发来的音信/n”; $buf = socket_read($msgsock, 8192); echo
“收到的新闻: $buf /n”; socket_close($msgsock); } while (true);
socket_close($sock); ?>

复制代码 代码如下:

到php.ini开启extension=php_sockets.dll,然后重启apache本事立竿见影。若无打开也许重启阿帕奇会出现Call
to undefined function socket_create()的报错。

聊起底自个儿依据 第三种情景写了三个 class

client端:

<?php
$fp = fsockopen(“127.0.0.1”, 10008, &$errno, &$errstr, 10);
if (!$fp) {
echo $errstr . ” (“. $errno . “)<br>n”;
} else {
$in = “HEAD / http/1.1\r\n”;
$in .= “HOST: localhost \r\n”;
$in .= “Connection: close\r\n\r\n”;
fputs($fp, $in);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}

第二步:使用socket

////////////////////////////// File Description
//////////////////////////////////////////
//  Class Name            : socket
//  Version               : V1.0
//  Functional Outline    : create socket,and send message to server
//  Revision history      : 2004/12/15 First version created
//  Current               : 2004/12/15 Liu Yongsheng
//////////////////////////////////////////////////////////////////////////////////////////
class socket{
 var $socket; //socket 句柄
 var $sendflag = “>>>”;
 var $recvflag = “<<<“;
 var $response;
 var $debug = 1;
 function socket($hostname,$port){
  $address = gethostbyname($hostname);
  $this->socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
     $result =  socket_connect($this->socket,$address,$port);
  if($this->debug == 1){
   if ($result < 0) {
      echo “socket_connect() failed.\nReason: ($result) ” .
socket_strerror($result) . “<br>”;
   } else{
      echo “connect OK.<br>”;
   }
  }  
 }
 function sendmsg($msg){
  socket_write($this->socket,$msg,strlen($msg));
  $result  = socket_read($this->socket,100);
  $this->response = $result;
  if($this->debug == 1){
      printf(“<font color=#CCCCCC>%s
$msg</fon><br>”,$this->sendflag);
      printf(“<font color=blue>%s
$result</font><br>”,$this->recvflag);
  }
        return $result;
 }
 function close(){
  socket_close($this->socket);
bf88必发唯一官网, }

<?php /** * 客户端代码 */ error_reporting(0);
set_time_limit(0); echo ” TCP/IP Connection /n”; $service_port =
10001; $address = ‘127.0.0.1’; $socket = socket_create(AF_INET,
SOCK_STREAM, SOL_TCP); if ($socket === false) { die; } else { echo
“OK”; } echo “试图连接 “; if (socket_connect($socket, $address,
$service_port) == false) { $error =
socket_strerror(socket_last_error()); echo “socket_connect()
failed./n”,”Reason: {$error} /n”; die; } else { echo “连接OK/n”; } $in =
“Hello World/r/n”; if (socket_write($socket, $in, strlen($in)) ===
false) { echo “socket_write() failed: reason: ” .
socket_strerror(socket_last_error()) .”/n”; die; } else { echo
“发送到服务器音信成功!/n”,”发送的剧情为: $in /n”; } $out = “”; while
($out = socket_read($socket, 8192)) { echo “接受的内容为: “.$out; }
echo “关闭SOCKET…/n”; socket_close($socket); echo “关闭OK/n”; ?>

您或然感兴趣的小说:

  • php中fsockopen用法实例
  • php使用fsockopen函数发送post,get央浼获取网页内容的不二等秘书籍
  • PHP的fsockopen、pfsockopen函数被主机商禁止使用的消除办法
  • php定期安排任务与fsockopen持续进度实例
  • php fsockopen解决办法
    php完结四线程
  • 浅析虚构主机服务器php
    fsockopen函数被剥夺的消除办法
  • php
    fsockopen伪造post与get方法的详解
  • php
    fsockopen中二十四线程难题的化解办法[翻译]
  • 通知三个用PHP
    fsockopen写的HTTP下载的类
  • php源码
    fsockopen获取网页内容实例详解

PHP socket专门的学问流程是:

}

 

1.创建socket   socket_create()

您或者感兴趣的作品:

  • 浅析:通过php
    socket并借助telnet达成轻易的闲话程序
  • 依赖PHP
    Socket配置以及实例的详尽介绍
  • 深深php
    socket的助教与实例分析
  • 基于php
    socket(fsockopen)的行使实例深入分析
  • PHP异步调用socket达成代码
  • php空间不帮助socket但扶助curl时recaptcha的用法
  • php获取远程图片的两种CU途乐L情势和sockets情势获得远程图片
  • php中使用Curl、socket、file_get_contents三种艺术POST提交数据
  • php模拟socket一回一连,数次发送数据的兑当代码
  • php HandlerSocket的使用
  • PHP Socket 编程
  • php
    win下Socket方式发邮件类
  • php
    socket格局提交的post详解
  • PHP达成Socket服务器的代码
  • 在PHP中动用Sockets
    从Usenet中获得文件
  • 在php中利用sockets:从新闻组中获取小说
  • 运用php通过Socket实行发信源码,协理发信认证
  • 浅析PHP Socket技术

再看websocket协议,是HTTP协议晋级来的。看其音讯头:

2.尝试通过创造的socket连接目的ip
 socket_connect(),注意了,这里不得不写ip,只好写ip,作者写localhost就错了。

 

3.获取连接结果,假诺连接成功,我们就足以传承开始展览自个儿要做的事务,假若退步,大家做三个后续要做的事情。

bf88必发唯一官网 1

4.关闭socket  socket_close()

 

PHP socket诉求示例:

就此server端供给分析一下,并回到握手的合计内容:

<?php
error_reporting(E_ALL);

echo “<h2>TCP/IP连接流程</h2>\n”;

/* 获取网址服务器端口 */
$service_port = getservbyname(‘www’, ‘tcp’);

/* 获取服务器的ip地址. */
$address = gethostbyname(‘www.wangtuizhijia.com’);

/* 创建TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo “socket_create() failed: reason: ” .
socket_strerror(socket_last_error()) . “\n”;
} else {
echo “socket_create创立成功\n”;
}

echo “尝试通过’$service_port’端口连接’$address’ …”.”<br>”;
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo “socket_connect() 连接失败: ($result) ” .
socket_strerror(socket_last_error($socket)) . “\n”;
} else {
echo “连接端口成功.”.”<br>”;
}

$in = “HEAD / HTTP/1.1″.”<br>”;
$in .= “Host: www.wangtuizhijia.com”.”<br>”;
$in .= “连接关闭”.”<br>”;
$out = ”;

echo “发送HTTP HEAD请求…”.”<br>”;
socket_write($socket, $in, strlen($in));
echo “成功”.”<br>”;

echo “响应音讯:”.”<br>”;
while ($out = socket_read($socket, 2048)) {
echo $out.”<br>”;
}

echo “关闭socket…”.”<br>”;
socket_close($socket);
echo “结束.\n\n”;
?>

在互连网找到分析的连锁代码 phpwebsocket – url:
  

结果:

 

TCP/IP连接流程

socket_create成立成功 尝试通过’80’端口连接’103.76.85.67′ …
连年端口成功.
发送HTTP HEAD请求…
成功
一呼百应新闻:
HTTP/1.1 400 Bad Request Content-Length: 311 Content-Type: text/html;
charset=us-ascii Server: Microsoft-HTTPAPI/2.0 Date: Mon, 08 May 2017
06:17:10 GMT Connection: close
关闭socket…
结束.

// Usage: $master=new WebSocket(“localhost”,12345); class WebSocket{ var
$master; var $sockets = array(); var $users = array(); var $debug =
false; function __construct($address,$port){ error_reporting(E_ALL);
set_time_limit(0); ob_implicit_flush();
$this->master=socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or
die(“socket_create() failed”); socket_set_option($this->master,
SOL_SOCKET, SO_REUSEADDR, 1) or die(“socket_option() failed”);
socket_bind($this->master, $address, $port) or die(“socket_bind()
failed”); socket_listen($this->master,20) or die(“socket_listen()
failed”); $this->sockets[] = $this->master;
$this->say(“Server Started : “.date(‘Y-m-d H:i:s’));
$this->say(“Listening on : “.$address.” port “.$port);
$this->say(“Master socket : “.$this->master.”/n”); while(true){
$changed = $this->sockets;
socket_select($changed,$write=NULL,$except=NULL,NULL); foreach($changed
as $socket){ if($socket==$this->master){
$client=socket_accept($this->master); if($client<0){
$this->log(“socket_accept() failed”); continue; } else{
$this->connect($client); } } else{ $bytes =
@socket_recv($socket,$buffer,2048,0); if($bytes==0){
$this->disconnect($socket); } else{ $user =
$this->getuserbysocket($socket); if(!$user->handshake){
$this->dohandshake($user,$buffer); } else{
$this->process($user,$this->unwrap($buffer)); } } } } } } function
process($user,$msg){ /* Extend and modify this method to suit your
needs */ /* Basic usage is to echo incoming messages back to client
*/ $this->send($user->socket,$msg); } function
send($client,$msg){ $this->say(“> “.$msg); $msg =
$this->wrap($msg); socket_write($client,$msg,strlen($msg));
$this->say(“! “.strlen($msg)); } function connect($socket){ $user =
new User(); $user->id = uniqid(); $user->socket = $socket;
array_push($this->users,$user);
array_push($this->sockets,$socket); $this->log($socket.”
CONNECTED!”); $this->log(date(“d/n/Y “).”at “.date(“H:i:s T”)); }
function disconnect($socket){ $found=null; $n=count($this->users);
for($i=0;$i<$n;$i++){ if($this->users[$i]->socket==$socket){
$found=$i; break; } } if(!is_null($found)){
array_splice($this->users,$found,1); }
$index=array_search($socket,$this->sockets); socket_close($socket);
$this->log($socket.” DISCONNECTED!”); if($index>=0){
array_splice($this->sockets,$index,1); } } function
dohandshake($user,$buffer){ $this->log(“/nRequesting handshake…”);
$this->log($buffer); list($resource,$host,$origin,$key1,$key2,$l8b) =
$this->getheaders($buffer); $this->log(“Handshaking…”); //$port
= explode(“:”,$host); //$port = $port[1];
//$this->log($origin.”/r/n”.$host); $upgrade = “HTTP/1.1 101
WebSocket Protocol Handshake/r/n” . “Upgrade: WebSocket/r/n” .
“Connection: Upgrade/r/n” . //”WebSocket-Origin: ” . $origin . “/r/n” .
//”WebSocket-Location: ws://” . $host . $resource . “/r/n” .
“Sec-WebSocket-Origin: ” . $origin . “/r/n” . “Sec-WebSocket-Location:
ws://” . $host . $resource . “/r/n” . //”Sec-WebSocket-Protocol:
icbmgame/r/n” . //Client doesn’t send this “/r/n” .
$this->calcKey($key1,$key2,$l8b) . “/r/n”;// . //”/r/n”;
socket_write($user->socket,$upgrade.chr(0),strlen($upgrade.chr(0)));
$user->handshake=true; $this->log($upgrade); $this->log(“Done
handshaking…”); return true; } function calcKey($key1,$key2,$l8b){
//Get the numbers preg_match_all(‘/([/d]+)/’, $key1, $key1_num);
preg_match_all(‘/([/d]+)/’, $key2, $key2_num); //Number crunching
[/bad pun] $this->log(“Key1: ” . $key1_num =
implode($key1_num[0]) ); $this->log(“Key2: ” . $key2_num =
implode($key2_num[0]) ); //Count spaces preg_match_all(‘/([
]+)/’, $key1, $key1_spc); preg_match_all(‘/([ ]+)/’, $key2,
$key2_spc); //How many spaces did it find? $this->log(“Key1 Spaces:
” . $key1_spc = strlen(implode($key1_spc[0])) ); $this->log(“Key2
Spaces: ” . $key2_spc = strlen(implode($key2_spc[0])) );
if($key1_spc==0|$key2_spc==0){ $this->log(“Invalid key”);return; }
//Some math $key1_sec = pack(“N”,$key1_num / $key1_spc); //Get the
32bit secret key, minus the other thing $key2_sec = pack(“N”,$key2_num
/ $key2_spc); //This needs checking, I’m not completely sure it should
be a binary string return md5($key1_sec.$key2_sec.$l8b,1); //The
result, I think } function getheaders($req){ $r=$h=$o=null;
if(preg_match(“/GET (.*) HTTP/” ,$req,$match)){ $r=$match[1]; }
if(preg_match(“/Host: (.*)/r/n/” ,$req,$match)){ $h=$match[1]; }
if(preg_match(“/Origin: (.*)/r/n/” ,$req,$match)){ $o=$match[1]; }
if(preg_match(“/Sec-WebSocket-Key1: (.*)/r/n/”,$req,$match)){
$this->log(“Sec Key1: “.$sk1=$match[1]); }
if(preg_match(“/Sec-WebSocket-Key2: (.*)/r/n/”,$req,$match)){
$this->log(“Sec Key2: “.$sk2=$match[1]); }
if($match=substr($req,-8)) { $this->log(“Last 8 bytes:
“.$l8b=$match); } return array($r,$h,$o,$sk1,$sk2,$l8b); } function
getuserbysocket($socket){ $found=null; foreach($this->users as
$user){ if($user->socket==$socket){ $found=$user; break; } } return
$found; } function say($msg=””){ echo $msg.”/n”; } function
log($msg=””){ if($this->debug){ echo $msg.”/n”; } } function
wrap($msg=””){ return chr(0).$msg.chr(255); } function unwrap($msg=””){
return substr($msg,1,strlen($msg)-2); } } class User{ var $id; var
$socket; var $handshake; }

 

 

笔者博客:PHP
Socket(套接字连接)扩充简要介绍和动用格局

承接类:能够团结按需写,这里本身增加了几行代码,sendAll()等,很有益就改成了八个及时的网页版聊天室。

 

// Run from command prompt > php -q chatbot.demo.php include
“websocket.class.php”; // Extended basic WebSocket as ChatBot class
ChatBot extends WebSocket{ function process($user,$msg){ if
(isset($user->first)) { $this->send($user->socket,”);
$user->first = true; } $this->say(“< “.$msg); switch($msg){
case “hello” : $this->send($user->socket,”hello human”); break;
case “hi” : $this->send($user->socket,”zup human”); break; case
“name” : $this->send($user->socket,”my name is Multivac, silly I
know”); break; case “age” : $this->send($user->socket,”I am older
than time itself”); break; case “date” :
$this->send($user->socket,”today is “.date(“Y.m.d”)); break; case
“time” : $this->send($user->socket,”server time is
“.date(“H:i:s”)); break; case “thanks”:
$this->send($user->socket,”you’re welcome”); break; case “bye” :
$this->send($user->socket,”bye”); break; //default :
$this->send($user->socket,$msg.” not understood”); break; default
: $this->sendAll($user, $msg); break; } } function
sendAll($currentUser, $msg){ $usersList = $this->users; foreach
($usersList as $user){ if ($user !== $currentUser) //
自己发送的音信就不再接受一次了 $this->send($user->socket, $msg); }
} } $master = new ChatBot(“localhost”,12345);

 

 

 

客户端代码:

 

<html>

<head>

<title>WebSocket</title>

 

<style>

 html,body{font:normal 0.9em arial,helvetica;}

 #log {width:440px; height:200px; border:1px solid #7F9DB9;
overflow:auto;}

 #msg {width:330px;}

</style>

 

<script>

var socket;

 

function init(){

  var host = “ws://localhost:12345/websocket/server.php”;

  try{

    socket = new WebSocket(host);

    log(‘WebSocket – status ‘+socket.readyState);

    socket.onopen    = function(msg){ log(“Welcome – status
“+this.readyState); };

    socket.onmessage = function(msg){ log(“Received: “+msg.data); };

    socket.onclose   = function(msg){ log(“Disconnected – status
“+this.readyState); };

  }

  catch(ex){ log(ex); }

  $(“msg”).focus();

}

 

function send(){

  var txt,msg;

  txt = $(“msg”);

  msg = txt.value;

  if(!msg){ alert(“Message can not be empty”); return; }

  txt.value=””;

  txt.focus();

  try{ socket.send(msg); log(‘Sent: ‘+msg); } catch(ex){ log(ex); }

}

function quit(){

  log(“Goodbye!”);

  socket.close();

  socket=null;

}

 

// Utilities

function $(id){ return document.getElementById(id); }

function log(msg){ $(“log”).innerHTML+=”<br>”+msg; }

function onkey(event){ if(event.keyCode==13){ send(); } }

</script>

 

</head>

<body onload=”init()”>

 <h3>WebSocket v2.00</h3>

 <div id=”log”></div>

 <input id=”msg” type=”textbox” onkeypress=”onkey(event)”/>

 <button onclick=”send()”>Send</button>

 <button onclick=”quit()”>Quit</button>

 <div>Commands: hello, hi, name, age, date, time, thanks,
bye</div>

</body>

</html>

 

 

PS:

*  那么些websocket的类公事大概有好几标题,客户端握手后应该吸收接纳的第一条新闻都遗落了,没细看代码,现在再检查吗。

 

版权注明:本文为博主原创小说,未经博主允许不得转发。


发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图