简体   繁体   中英

Sending huge strings over TCP (Java - PHP)

Okay, so i'm running a server that contains alot of data about different things. (It's a minecraft server)

Now, i'm creating a website for that server and i'm having a PHP script send for the data from the server and the server returns as much data as it can. (It cuts off somewhere in the middle)

I know how to make a java server send chunks of a string to another java client, but i am unfamiliar with how to do it in PHP.

This is my PHP script:

<?php
$PORT = 4321;
$HOST = "78.70.152.57";

$name = $_POST['name'];

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

$succ = socket_connect($sock, $HOST, $PORT)
or die("UNREACHABLE\n");

$text = "AUCTIONS>MONEY:".$name;

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

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

echo $reply;
?>

Also providing my server code, just in case:

  BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));

  String message = input.readLine();
  Main.console.sendMessage(message);
  String response = "";
  if(message.contains(">")) {
    String[] messages = message.split(">");
    for(String value : messages) {
         response += getResponse(value)+">";
    }
    response = response.substring(0, response.length()-1);
    } else {
    response = getResponse(message);
}

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
if(response != "") {
    out.write(response);
} else {
    out.write("SERVER-RESPONSE-INVALID");
}
out.flush();

input.close();
out.close();

Note: Only the part where it recieves the message and responds is here.

Note2: I'm using an AJAX POST code to get what the PHP script echoes, if that's important.

Right now, you read "upto" 10000 bytes of data and cut it off after that. What you want to do is read from the socket until there is no data left:

$reply = '';
while(true) {
    $chunk = @socket_read($sock, 10000);

    if (strlen($chunk) == 0) {
        // no more data
        break;
    }

    $reply .= $chunk;
}

echo $reply;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM