将数据从PHP发送到Java tcp侦听器

时间:2013-05-30 12:32:33

标签: java php

所以,我有一个非常基本的测试设置,看看我是否可以将数据从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的响应,但似乎没有工作。我得到一个连接OK和数据发送正常,但服务器没有打印任何东西也没有回应任何东西,所以我不知道为什么它说它没关系:))

方法1

$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);
}

方法2

$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 doesnt return anything找到的评论连接到localhost时出现问题,因此更改为127.0.0.1但仍无法正常工作。

1 个答案:

答案 0 :(得分:0)

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

     outToClient.writeBytes(capitalizedSentence);
     connectionSocket.close()