Python套接字服务器到PHP客户端套接字
我正在尝试在Python和PHP之间建立套接字连接。Python将充当服务器,PHP将充当客户端。我想启动这个网页并检查Python中的线程是否正在运行,所以我将一个变量发送到PHP的套接字中。这很有效。加载页面后,用户可以单击按钮启用或禁用线程。因此,这些按钮返回一个变量enable/disable。但我无法将这些数据发送回套接字。如何将按钮按下数据恢复到插座中Python套接字服务器到PHP客户端套接字,php,python,sockets,Php,Python,Sockets,我正在尝试在Python和PHP之间建立套接字连接。Python将充当服务器,PHP将充当客户端。我想启动这个网页并检查Python中的线程是否正在运行,所以我将一个变量发送到PHP的套接字中。这很有效。加载页面后,用户可以单击按钮启用或禁用线程。因此,这些按钮返回一个变量enable/disable。但我无法将这些数据发送回套接字。如何将按钮按下数据恢复到插座中 import time import socket import logging def socketCon(): LOG
import time
import socket
import logging
def socketCon():
LOG_FILENAME = "logging.out"
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
logging.info("Started setting up the socket to php connection")
HOST = '127.0.0.1' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
logging.info("Connected to Server")
except socket.error, msg:
logging.info('Socket Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
s = None
continue
try:
s.bind(sa)
logging.info("Bind Complete")
s.listen(1)
logging.info("Now Listening to socket")
except socket.error, msg:
logging.info('Socket bind/listening Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
s.close()
s = None
continue
break
if s is None:
logging.info("could not open socket")
#try:
logging.info("Waiting on Socket to Accept")
conn, addr = s.accept()
logging.info("Connected by "+str(addr))
# Get data from the socket
#data1 = conn.recv(1024)
#logging.info("What did the user send from the Website: "+str(data1))
# Send data to socket
alarm = "Enabled"
conn.send(alarm)
logging.info("Send status to client socket: "+str(alarm))
run = True
logging.info("Waiting for user button press")
# Wait for user button press from website
while run == True:
# Get the button press from the website
data2 = conn.recv(1024)
logging.info("Recieving data: "+str(data2))
if data2 == 0:
logging.info("What did the user select from the Website: "+str(data2))
run = False
# close the socket
conn.close()
def runTest():
#while:
try:
socketCon()
except:
print "There was a problem"
socketCon()
#runTest()
PHP客户端:
if(isset($_SESSION['id']))
{
// Put stored session variables into local PHP variable
$uid = $_SESSION['id'];
$usname = $_SESSION['username'];
$result = "Login data: <br /> Username: ".$usname. "<br /> Id: ".$uid;
error_reporting(E_ALL);
// Allow the script to hang around waiting for connections.
set_time_limit(0);
// Turn on implicit output flushing so we see what we're getting as it comes in.
ob_implicit_flush();
// Set timeout in seconds
$timeout = 3;
// Create a TCP/IP client socket.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
{
$result2 = "Error: socket_create() failed: reason: " .socket_strerror(socket_last_error()). "\n";
}
// Server data
$host = '127.0.0.1';
$port = 50007;
$error = NULL;
$attempts = 0;
$timeout *= 1000; // adjust because we sleeping in 1 millisecond increments
$connected = FALSE;
while (!($connected = socket_connect($socket, $host, $port)) && ($attempts++ < $timeout))
{
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY)
{
echo "Error Connecting Socket: ".socket_strerror($error) . "\n";
socket_close($socket);
return NULL;
}
usleep(1000);
}
if (!$connected)
{
echo "Error Connecting Socket: Connect Timed Out After " . $timeout/1000 . " seconds. ".socket_strerror(socket_last_error()) . "\n";
socket_close($socket);
return NULL;
}
// Write to the socket
//$output="Client Logged on via website" ;
//socket_write($socket, $output, strlen ($output)) or die("Could not write output\n");
// Get the response from the server - our current telemetry
$resultLength = socket_read($socket, 1024) or die("Could not read server response\n");
$result4 = $resultLength;
if($result4 === "Enabled")
{
echo "Alarm is Running";
$disabled1 = "disabled='disabled'";
$disabled2 = "";
}
elseif($result4 === "Disabled")
{
echo "Alarm is not running";
$disabled1 = "";
$disabled2 = "disabled='disabled'";
}
// close the socket
socket_close($socket);
}
else
{
$result = "You are not logged in yet";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title><?php echo $usname ;?> - Alarm Enable/Disable</title>
</head>
<body>
<br>
<?php
echo $result;
?>
<br>
<?php
echo $result2;
?>
<br>
<form id="form" action="user.php" method="post" enctype="multipart/form-data">
<input type='submit' name='submit1' value='Enable Alarm' <?php echo $disabled1; ?> />
<input type='submit' name='submit2' value='Disable Alarm' <?php echo $disabled2; ?> />
</form>
<article>
<?php
if (isset($_POST[submit1]))
{
/*// Allow the script to hang around waiting for connections.
set_time_limit(0);
// Turn on implicit output flushing so we see what we're getting as it comes in.
ob_implicit_flush();
// Set timeout in seconds
$timeout = 3;
// Create a TCP/IP client socket.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
{
$result2 = "Error: socket_create() failed: reason: " .socket_strerror(socket_last_error()). "\n";
}
// Server data
$host = '127.0.0.1';
$port = 50007;
$error = NULL;
$attempts = 0;
$timeout *= 1000; // adjust because we sleeping in 1 millisecond increments
$connected = FALSE;
while (!($connected = socket_connect($socket, $host, $port)) && ($attempts++ < $timeout))
{
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY)
{
echo "Error Connecting Socket: ".socket_strerror($error) . "\n";
socket_close($socket);
return NULL;
}
usleep(1000);
}
*/
if (!$connected)
{
echo "Error Connecting Socket: Connect Timed Out After " . $timeout/1000 . " seconds. ".socket_strerror(socket_last_error()) . "\n";
socket_close($socket);
return NULL;
}
// Write to the socket
$input="Enable";
socket_write($socket, $input, strlen ($input)) or die("Could not write input\n");
echo "Send Enable back into socket to the Server";
// close the socket
socket_close($socket);
// Now direct to user feed
header("Location: logout.php");
}
if (isset($_POST[submit2]))
{
/*// Allow the script to hang around waiting for connections.
set_time_limit(0);
// Turn on implicit output flushing so we see what we're getting as it comes in.
ob_implicit_flush();
// Set timeout in seconds
$timeout = 3;
// Create a TCP/IP client socket.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false)
{
$result2 = "Error: socket_create() failed: reason: " .socket_strerror(socket_last_error()). "\n";
}
// Server data
$host = '127.0.0.1';
$port = 50007;
$error = NULL;
$attempts = 0;
$timeout *= 1000; // adjust because we sleeping in 1 millisecond increments
$connected = FALSE;
while (!($connected = socket_connect($socket, $host, $port)) && ($attempts++ < $timeout))
{
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY)
{
echo "Error Connecting Socket: ".socket_strerror($error) . "\n";
socket_close($socket);
return NULL;
}
usleep(1000);
}
*/
if (!$connected)
{
echo "Error Connecting Socket: Connect Timed Out After " . $timeout/1000 . " seconds. ".socket_strerror(socket_last_error()) . "\n";
socket_close($socket);
return NULL;
}
// Write to the socket
$input="Disable";
socket_write($socket, $input, strlen ($input)) or die("Could not write input\n");
echo "Send Disable back into socket to the Server";
// close the socket
socket_close($socket);
// Now direct to user feed
header("Location: logout.php");
}
?>
</article>
<br>
<a href="logout.php">Logout</a>
</body>
</html>
if(isset($\u会话['id']))
{
//将存储的会话变量放入本地PHP变量
$uid=$\会话['id'];
$usname=$\会话['username'];
$result=“登录数据:
用户名:“.usname”。
标识:“.uid;
错误报告(E_全部);
//允许脚本挂起等待连接。
设置时间限制(0);
//打开隐式输出刷新,这样我们就可以看到它进入时得到了什么。
ob_implicit_flush();
//以秒为单位设置超时
$timeout=3;
//创建TCP/IP客户端套接字。
$socket=socket\u create(AF\u INET、SOCK\u STREAM、SOL\u TCP);
如果($socket==false)
{
$result2=“Error:socket\u create()失败:原因:”.socket\u strerror(socket\u last\u Error())。“\n”;
}
//服务器数据
$host='127.0.0.1';
$port=50007;
$error=NULL;
$truments=0;
$timeout*=1000;//调整,因为我们以1毫秒为增量睡眠
$connected=FALSE;
而(!($connected=socket\u connect($socket,$host,$port))&($attempts++<$timeout))
{
$error=socket_last_error();
如果($error!=SOCKET\u EINPROGRESS&$error!=SOCKET\u EALREADY)
{
echo“连接套接字时出错:”.Socket\u strerror($Error)。“\n”;
插座关闭($socket);
返回NULL;
}
usleep(1000);
}
如果(!$connected)
{
echo“连接套接字时出错:连接在“$timeout/1000.”秒之后超时。”.Socket\u strerror(Socket\u last\u Error())。“\n”;
插座关闭($socket);
返回NULL;
}
//写入套接字
//$output=“客户端通过网站登录”;
//socket_write($socket,$output,strlen($output))或die(“无法写入输出”);
//从服务器获取响应-我们当前的遥测
$resultLength=socket\u read($socket,1024)或die(“无法读取服务器响应\n”);
$result4=$resultLength;
如果($result4==“已启用”)
{
回声“警报正在运行”;
$disabled1=“disabled='disabled'”;
$disabled2=“”;
}
elseif($result4==“已禁用”)
{
回显“报警未运行”;
$disabled1=“”;
$disabled2=“disabled='disabled'”;
}
//合上插座
插座关闭($socket);
}
其他的
{
$result=“您尚未登录”;
}
?>
-报警启用/禁用
/>
好的,我找到了解决方案。我需要定义一个循环来获取s.accept(),这样当客户端想要连接到服务器时,它就会获得新的adrr值。要解决这个问题,您需要将s.accept()放入一个循环中。这将确保连接保持建立状态