0

所以,我有一个非常基本的测试设置,看看我是否可以将数据从 php 网页发送到运行在同一台服务器上的 java 应用程序。

Java 应用程序非常简单,它只是在 TCP 套接字上侦听数据

import java.io.*;
import java.net.*;

class TCPServer
{
   public static void main(String argv[]) throws Exception
      {
         String clientSentence;
         String capitalizedSentence;
         ServerSocket welcomeSocket = new ServerSocket(6789);

         while(true)
         {
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient =
               new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            System.out.println("Received: " + clientSentence);
            capitalizedSentence = clientSentence.toUpperCase() + '\n';
            outToClient.writeBytes(capitalizedSentence);
            connectionSocket.close(); //this line was part of the solution
         }
      }
}

我尝试了两种使用 php 发送和读取响应的方法,但似乎都不起作用。我的连接正常,数据发送正常,但是服务器没有打印任何东西,也没有响应任何东西,所以我不知道为什么它说没问题 :)

方法一

$host = "tcp://localhost"; 
$port = 6789;
$data = 'test' . PHP_EOL;  //Adding PHP_EOL was the other part of the solution
$errstr = '';
$errno = '';

if ( ($fp = fsockopen($host, $port, $errno, $errstr, 3) ) === FALSE)
    echo "$errstr ($errno)";
else {
    print 'SUCCESS!<br />';
    fwrite($fp, $data);
    while (! feof($fp)) {
      echo fgets($fp, 4096);
    }
    fclose($fp);
}

方法二

$host = "localhost"; 
$port = 6789;
$data = 'test';

if ( ($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === FALSE )
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error());
else 
{
    echo "Attempting to connect to '$host' on port '$port'...<br>";
    if ( ($result = socket_connect($socket, $host, $port)) === FALSE )
        echo "socket_connect() failed. Reason: ($result) " . socket_strerror(socket_last_error($socket));
    else {
        echo "Sending data...<br>";
        socket_write($socket, $data, strlen($data));
        echo "OK<br>";

        echo "Reading response:<br>";
        while ($out = socket_read($socket, 2048)) {
            echo $out;
        }
    }
    socket_close($socket);      
}

编辑

显然 fsockopen() 从我在PHP fsockopen 发现的评论中连接到 localhost 时出现问题 fsockopen 没有返回任何内容,因此更改为 127.0.0.1 但仍然无法正常工作。

4

1 回答 1

0
  • 尝试更改$data = 'test'$data = "test\n",看看是否有帮助。
  • 完成后关闭服务器上的套接字,否则客户端将阻塞在while循环中等待更多数据:

     outToClient.writeBytes(capitalizedSentence);
     connectionSocket.close()
    
于 2013-05-30T12:42:21.410 回答