我正在为java编写服务器套接字,它从客户端套接字获取数据,处理它们并发回响应。
在当前状态下,我能够发送数据并对其进行处理,但遗憾的是,我无法弄清楚如何将处理后的数据从服务器套接字发送到客户端套接字。我已经尝试使用php.net提供的示例,但这只是阻止了我的数据发送。我也试图只读或写,这就像一个魅力。
我的服务器套接字(java)如下所示:
public class TcpListener {
public static String clientSentence;
private static ServerSocket serverSocket;
public static void main(String argv[]) throws Exception{
serverSocket = new ServerSocket(49654);
Socket connectionSocket = serverSocket.accept();
while(true)
{
//read
int reportId = read(connectionSocket);
//write
write(connectionSocket, reportId);
}
//connectionSocket.close();
}
public static int read(Socket connectionSocket) throws IOException{
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
Report r = new Report(clientSentence);
int reportId = r.main();
inFromClient.close();
return reportId;
}
public static void write(Socket connectionSocket, int id) throws IOException{
PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(), true);
System.out.println(id);
outToClient.println(id);
outToClient.flush();
outToClient.close();
}
}
和我的客户端套接字(php):
set_time_limit(0);
ob_implicit_flush();
$host = "localhost";
$port = 49654;
if (($socket = socket_create(AF_INET, SOCK_STREAM, 0)) === false) {
echo "\nsocket_create() failed: reason: " . socket_strerror(socket_last_error());
} else {
echo "\nAttempting to connect to '$host' on port '$port'...\n";
if (($result = socket_connect($socket, $host, $port)) === false) {
echo "socket_connect() failed. Reason: ($result) " . socket_strerror(socket_last_error($socket));
} else {
socket_set_nonblock($socket);
echo "Sending data...\n";
$sresult = socket_send($socket, $message."\r\n", strlen($message), MSG_DONTROUTE);
if ($sresult === false) {
$errorcode = socket_last_error($socket);
$errormsg = socket_strerror($errorcode);
die("error sending data. " . $errormsg. "($errorcode)");
}
echo "OK\n";
echo "Reading response:\n\n";
while(socket_recv ( $socket , $buf , 2045 , MSG_WAITALL ) === FALSE){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
echo $buf;
}
echo "close";
socket_close($socket);
}
正在显示以下错误消息:
Warning: socket_recv(): unable to read from socket [10045]: The attempted operation is not supported for the type of object
referenced. <b>D:\xampp\htdocs\api\select\getApps.php</b> on line <b>75</b><br />
Could not receive data: [10045] The attempted operation is not supported for the type of object referenced.
第75行是while
循环。
我很感激有关如何解决问题的任何帮助。