我通过套接字传输字符串数据,数据传输完美但速度很慢。
我的Java客户端有以下代码(它是一个bukkit服务器插件):
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) {
}
}
数据字符串最终保持值{"server": {"name": "Gaming Node 2","onlineplayers": "1","maxplayers": "20"}}}
我的PHP客户端有以下代码:
<?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 \n");
}
echo "Socket created \n";
//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 \n");
}
echo "Connection established \n";
$message = "GET / HTTP/1.1\r\n\r\n";
//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 \n");
}
echo "Message send successfully \n";
//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 \n");
}
//print the received message
echo $buf;
socket_close($sock);
?>
数据传输成功但大约需要10秒钟。如果我将java端的数据字符串缩短,可能是一个单词,则大约需要1.5秒。我不认为这是一个网络连接速度问题,因为它们都在同一台机器上运行(我是否需要在php脚本区域中编写本地主机以利用它们在同一台机器上的事实? )。如何更快地传输数据?