I am transferring String data through sockets, the data transfers perfectly but slowly.
My Java Client has the following code (It is a bukkit server plugin):
while(true) {
try {
ServerSocket SRVSOCK = new ServerSocket(25560);
Socket SOCK = SRVSOCK.accept();
InputStreamReader IR = new InputStreamReader(SOCK.getInputStream());
BufferedReader BR = new BufferedReader(IR);
String MESSAGE = BR.readLine();
System.out.println(MESSAGE);
if (MESSAGE != null) {
PrintStream PS = new PrintStream(SOCK.getOutputStream());
String data = "";
data += "{";
data += "\"server\": {";
data += "\"name\": \"" + getConfig().getString("data.name") + "\",";
data += "\"onlineplayers\": \"" + String.valueOf(getServer().getOnlinePlayers().length) + "\",";
data += "\"maxplayers\": \"" + String.valueOf(getServer().getMaxPlayers()) + "\"";
data += "}";
data += "}";
data += "}";
System.out.println(data);
PS.println(data);
}
} catch (Exception e) {
}
}
The Data String ends up holding the value {"server": {"name": "Gaming Node 2","onlineplayers": "1","maxplayers": "20"}}}
And my PHP client has the following code:
<?php
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg
");
}
echo "Socket created
";
//Connect socket to remote server
if(!socket_connect($sock ,gethostbyname("Ip.address.com"), 25560))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not connect: [$errorcode] $errormsg
");
}
echo "Connection established
";
$message = "GET / HTTP/1.1
";
//Send the message to the server
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg
");
}
echo "Message send successfully
";
//Now receive reply from server
if(socket_recv ( $sock , $buf , 2045 , MSG_WAITALL ) === FALSE)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg
");
}
//print the received message
echo $buf;
socket_close($sock);
?>
The data is transferred successfully but takes about 10 seconds. If I make the data string on the java side shorter, to maybe a word, it takes about 1.5 seconds. I don't think this is a network connection speed issue because they are both running on the same machine (do I need to write local host in the php script area to take advantage of the fact that they are on the same machine?). How do I make the transfer of data faster?