开发者

PHP/Java Sockets - Strange error?

Java code:

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 console (when I access the following PHP script):

listening
accepted
got reader

PHP code:

<?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;
?>

When I navigate to the PHP page, it loads forever.

Any ideas?


The Java side expects a newline in its input. You're not sending one, so readLine never finishes.

Also, readLine won't return null until the socket is closed or an exception occurs (I/O error for instance). You need to return some data as soon as you've read a line if your protocol works like that.


As it was told, you need to close socket to readLine returns null.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜