【问题标题】:PHP/Java Sockets - Strange error?PHP/Java 套接字 - 奇怪的错误?
【发布时间】:2011-10-03 08:06:24
【问题描述】:

Java 代码:

package servermonitor;

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

public class CommandListener extends Thread
{
    public int count = 0;
    public void run()
    {
            try
            {
                ServerSocket server = new ServerSocket(4444);
                while(true)
                {
                    System.out.println("listening");
                    Socket client = server.accept();
                    System.out.println("accepted");
                    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                    System.out.println("got reader");
                    String data = "";
                    String line;
                    while((line = in.readLine()) != null)
                    {
                        System.out.println("inloop");
                        data = data + line;
                    }
                    System.out.println("RECIEVED DATA: " + data);
                    in.close();
                    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
                    count++;
                    out.write("gotcha: " + count + "\\n");
                    out.flush();
                }

            }
            catch(IOException ex)
            {
                System.out.println(ex.getMessage());
            }

    }

 }

Java 控制台(当我访问以下 PHP 脚本时):

listening
accepted
got reader

PHP 代码:

<?php
$PORT = 4444; //the port on which we are connecting to the "remote" machine
$HOST = "localhost"; //the ip of the remote machine (in this case it's the same machine)

$sock = socket_create(AF_INET, SOCK_STREAM, 0) //Creating a TCP socket
or die("error: could not create socket\n");

$succ = socket_connect($sock, $HOST, $PORT) //Connecting to to server using that socket
or die("error: could not connect to host\n");

$text = "Hello, Java!\n"; //the text we want to send to the server

socket_write($sock, $text, strlen($text) + 1) //Writing the text to the socket
or die("error: failed to write to socket\n");

$reply = socket_read($sock, 10000) //Reading the reply from socket
or die("error: failed to read from socket\n");

echo $reply;
?>

当我导航到 PHP 页面时,它会永远加载。

有什么想法吗?

【问题讨论】:

  • 你确定它不会循环打印

标签: java php sockets


【解决方案1】:

Java 端在其输入中需要一个换行符。你没有发送,所以readLine 永远不会完成。

另外,readLine 在套接字关闭或发生异常(例如 I/O 错误)之前不会返回 null。如果您的协议是这样工作的,您需要在读取一行后立即返回一些数据。

【讨论】:

  • 嗯,这只是部分修复 - 我现在卡在 Java 控制台说“inloop”,页面仍然永远加载!
  • socket_send($sock,$text,strlen($text),0) //只发送信息,不接收
【解决方案2】:

如前所述,您需要关闭套接字才能 readLine 返回 null。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2011-05-17
    • 1970-01-01
    • 2012-05-03
    相关资源
    最近更新 更多