PHP套接字消息为null

时间:2012-10-29 20:45:12

标签: java php sockets

我在php中打开一个套接字并发送消息。当我尝试在此套接字中读取Java中的消息时,建立了连接,但消息为空?

有任何帮助吗? Cannot read response from Java socket server using PHP client这是我遇到的同样问题,但我确实在邮件中添加了\ n。

  // variables
        $host = gethostbyname('localhost');
        $port = 4444;   
        $message = $host." list\n\0";

        // create socket
        if (!($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);
            die("Couldn't create socket: [$errorcode] $errormsg \n");
        }
        echo "Socket created!\n";

        // connect
        if (!socket_connect($sock, $host, $port)) {
            $errorcode = socket_last_error();
            $errormsg = socket_strerror($errorcode);
            die("Couldn't connect: [$errorcode] $errormsg \n");
        }
        echo "Connection established!\n";
        echo $message;
        $length = strlen($message);
        // get room info - send message
        while(true){
            $sent=sock_write($sock, $message, 1024);
            if ($sent===false) {
                $errorcode = socket_last_error();
                $errormsg = socket_strerror($errorcode);
                die("Couldn't send data: [$errorcode] $errormsg \n");
            }
            // Check if the entire message has been sented
                if ($sent < $length) {

                // If not sent the entire message.
                // Get the part of the message that has not yet been sented as message
               $st = substr($msg, $sent);
               $message= $st;

                // Get the length of the not sented part
                $length -= $sent;

            } else {

                break;
            }


        }           

        echo "Message sent!\n";

和java方面

 while (true) { 

        try {

            socket = new ServerSocket(4444);


        } catch (UnknownHostException e) {
            System.err.println("Dont know about host: localhost.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to localhost");
            System.exit(1);
        }

        try {

            clientSocket = socket.accept();
            System.out.printf("Connected!\n");

        } catch (IOException e) {
            e.printStackTrace();
        }

        try {

            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);    //object to send data
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); //object to read data
            String inputLine, outputLine;
            inputLine = in.readLine();  //read data

            System.out.println(inputLine);

Java代码的运行方式类似于服务器的网关。

1 个答案:

答案 0 :(得分:0)

$sent=sock_write($sock, $message, 1024);

这应该是

$sent=sock_write($sock, $message, $length);

甚至$ length-1,因为Java对尾随空值不感兴趣。