doukao8851 2010-11-12 15:32
浏览 44
已采纳

PHP Socket Java消息交换

I'm trying to make a communication between a PHP page and running Java server. Just a simple string exchange through sockets.

This is my Java Code for thread that handles the connection:

            InputStream in = clientSocket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

                String request;

                if((request=br.readLine())!=null){
                System.out.println("got the following request: " + request);
                out.write(request +"
");
                out.flush();

                out.close();
                in.close();
                }

I tested it with simple Java client that sends the string then receives the result and prints it back and it worked. Both client and the server had the same output.

This is my PHP code:

$fp = @fsockopen ($host, $port, $errno, $errstr);

if($fp){
    fputs($fp, $str);
    //echo fgets($fp);
}

close($fp);

Which sends the string to the Server, and the Server receives it. But once I uncomment the line with fgets($fp) I am blocked until some sort of timeout happens after 1-2 minutes. During that Block my server is not receiving anything. After timeout my server prints, that it has received the line, and probably sends the response back, however, the PHP code doesn't print anything.

What could be the problem?

Thank you in advance.

P.S. It is probably worth saying that I am accessing this web page through AJAX, so it "echoes" the result back to the other page.

  • 写回答

3条回答 默认 最新

  • douguaidian8021 2010-11-12 23:45
    关注

    I prefer the socket_* functions, personally. But either way, you're likely missing checking for a terminating character:

    $sock = socket_create(AF_INET, SOCK_STREAM, 0);
    socket_connect($sock, $host, $port);
    
    socket_write($sock, $str);
    
    $response = '';
    while($resp = socket_read($sock, 1024)) {
        if(!$resp)
            break;
        $response .= $resp;
        if(strpos($resp, "
    ") !== false)
            break;
    }
    
    echo "Server said: {$response}";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发