我已经在 PHP 页面和 C++ 代码之间建立了一个 TCP Socket 连接。下面是这个连接的 C++ 代码。
Server.cpp
我在终端上运行Server.cpp文件,然后在浏览器上运行index.php。当我在浏览器上运行index.php并输入查询词“123456 7890”时,服务器会在终端上打印出消息"123456 7890"。
但是服务器无法将消息“我收到了你的消息”发送回浏览器上的index.php。只有当我按下Ctrl + C退出服务器时,它才会向index.php发送消息,然后index.php才会在浏览器上显示所有内容。 这里有什么问题? 我想在Server.cpp中监听套接字,并无限制地向index.php发送消息。
Server.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
int main(){
int create_socket,new_socket,fd;
int n;
socklen_t addrlen;
struct sockaddr_in address;
if ((create_socket = socket(AF_INET,SOCK_STREAM,0)) > 0)
cout<<"The socket was created\n";
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;//INADDR_ANY;inet_addr("localhost");
address.sin_port = htons(4000);
cout<<"\nworking";
if (bind(create_socket,(struct sockaddr *)&address,sizeof(address)) == 0)
cout<<"Binding Socket\n";
while(1){
listen(create_socket,3);
addrlen = sizeof(struct sockaddr_in);
cout<<"*************************\n";
new_socket = accept(create_socket,(struct sockaddr *)&address,&addrlen);
cout<<"*************************\n";
char dobj[1024];
if (new_socket > 0){
n = read(new_socket, dobj, 1023);
string query(dobj);
string strl(query);
string s, d;
istringstream iss(strl);
iss >> s;
iss >> d;
const char* source = s.c_str();
const char* dest = d.c_str();
printf("Here is the message: %s %s\n",source,dest);
n = write(new_socket, "I got your message", 18);
}
}
close(new_socket);
return close(create_socket);
}
PHP代码是index.php
<?php
if (isset($_GET['submit'])){
$query = $_GET['query'];
echo $query;
error_reporting(E_ALL);
$service_port = 4000;
$address = "localhost";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false){
echo "Failed: ". socket_strerror(socket_last_error($socket))."\n";
}
echo "Attempting to connect to '$address' on port '$service_port'...'\n";
$result = socket_connect($socket, $address, $service_port);
if ($result === false){
echo "Failed: ". socket_strerror(socket_last_error($socket))."\n";
}
$in = $query;
$out = '';
echo "Sending...\n";
socket_send($socket, $in, strlen($in), MSG_WAITALL);
echo "OK.\n";
echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
echo $out;
}
socket_close($socket);
}
?>
<html>
<head>
</head>
<body>
<form action="index.php" method="get">
Query: <input type="text" name="query">
<button type="submit" name="submit">Submit!</button>
</form>
</body>
</html>
我在终端上运行Server.cpp文件,然后在浏览器上运行index.php。当我在浏览器上运行index.php并输入查询词“123456 7890”时,服务器会在终端上打印出消息"123456 7890"。
但是服务器无法将消息“我收到了你的消息”发送回浏览器上的index.php。只有当我按下Ctrl + C退出服务器时,它才会向index.php发送消息,然后index.php才会在浏览器上显示所有内容。 这里有什么问题? 我想在Server.cpp中监听套接字,并无限制地向index.php发送消息。