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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c