如何在PHP中打破socket_accept? [英] How to break socket_accept in PHP?

查看:89
本文介绍了如何在PHP中打破socket_accept?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个与php socket相关的项目。我的目标是我将显示连接到服务器的所有客户端并在html文件中显示它们。但是,如果我在while循环中放入socket_accept()函数,则在没有客户端连接时它不会中断。现在,我想while循环只接受10秒内的所有客户端然后导出结果?如何在php中断开socket_accept?

I am doing a project related to php socket. My target is that I will show all client connected to server and show them in html file. However, if i put socket_accept() function in while loop, it won't break when no client connect. Now, I want to while loop only accept all client in 10 second and then export result? How to break socket_accept in php?

<pre><?php

error_reporting(E_ALL);	
/* Allow the script to hang around waiting for connections. */
set_time_limit(10);

	/* Turn on implicit output flushing so we see what we're getting
	* as it comes in. */
	ob_implicit_flush();
	
	$address = "103.1.239.148";
	$port = 10000;
	// Maximum device
	$maxdevice = 5;
	
	// Create Socket
	$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	if ($sock === false) {
		echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
	}
	
	if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) { 
		echo socket_strerror(socket_last_error($sock)); 
		exit; 
	}
	
	// Bind Socket to port
	if (socket_bind($sock, $address, $port) === false) {
		echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
	}
	
	// Start listening for connection
	if (socket_listen($sock, $maxdevice) === false) {
		echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
	}
	
	// Handling connection from client
	$i=0; // Initial count variable 
	while (true)
	{
		$msgsock[++$i] = socket_accept($sock); // msgsock is a client connect to webserver
		if ($msgsock[$i] === false) {
			echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
			break;
		}
		$senddata="L";
		socket_write($msgsock[$i], $senddata, strlen($senddata)) or die("Couldn't write to client");
		$receive=socket_read($msgsock[$i],2048,PHP_BINARY_READ) or die ("Couldn't read from client");
		if ($receive !="")
		{
			include ("list.html");
		}
		if ($i==$maxdevice)
			break;
		socket_close($msgsock[$i]);  // Close connect of client
	} 
	socket_close($sock);  // Close socket of server
	?>





我尝试过:



我尝试了set_time_limit()但它没有正常工作。



What I have tried:

I have tried set_time_limit() but it doesn't work fine.

推荐答案

address =103.1。 239.148;
address = "103.1.239.148";


port = 10000;
//最大设备
port = 10000; // Maximum device


maxdevice = 5;

//创建套接字
maxdevice = 5; // Create Socket


这篇关于如何在PHP中打破socket_accept?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆