[英]java tcp program too slow(on the same computer)
因此,基本上我在计算机广告上运行了2个Java应用程序,然后在我传输数据之后,我计算了通过Java tcp的传输速度,并且速度始终在7 MegaBits /秒左右,无论如何,我一直期望至少每秒56mbits,这是客户端应用程序:
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
System.out.println("Hello, World");
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 7);
BufferedInputStream inFromServer = new BufferedInputStream(clientSocket.getInputStream());
double count=0;
OutputStream socketOutputStream = clientSocket.getOutputStream();
String s = "012345678901234567\n";
byte[] bytes = s.getBytes();
final int BUFFER_SIZE = 65536;
byte[] buffer = new byte[BUFFER_SIZE];
// socketOutputStream.write(bytes);
// inFromServer.read(buffer);
// modifiedSentence = new String(buffer);
// System.out.println("FROM SERVER:" + modifiedSentence);
socketOutputStream.write(bytes);
long times=System.nanoTime() ;
long temp=times;long temp2=times;
while (true) {
socketOutputStream.write(bytes);
count++;
socketOutputStream.flush();
if(count>=100000){
break;
}
}
times=System.nanoTime() ;
System.out.println("time(ns) : " + (times-temp2));
double speed=(72*2*count)/(double)((times-temp2)*Math.pow(10,-9));
System.out.println("speed : " + speed/(1024*1024));
clientSocket.close();
}
}
这是服务器代码:
import java.io.*;
import java.net.*;
class TCPClient extends Thread
{
Socket clientSocket;
public TCPClient(Socket socket) {
super("KKMultiServerThread");
this.clientSocket = socket;
}
public void run() //throws Exception
{
System.out.println("Hello, World");
try {
String modifiedSentence;
BufferedOutputStream outToServer = new BufferedOutputStream(clientSocket.getOutputStream());
BufferedInputStream inFromServer = new BufferedInputStream(clientSocket.getInputStream());
double count=0;
String s = "012345678901234567\n";
byte[] bytes = s.getBytes();
long times=System.nanoTime() ;
long temp=times;long temp2=times;
final int BUFFER_SIZE = 19;
byte[] buffer = new byte[BUFFER_SIZE];
modifiedSentence = "";
while ((inFromServer.read(buffer))!=-1) {
// outToServer.write(bytes);
// outToServer.flush();
}
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
System.exit(1);
}
}
}
服务器代码已调整为不写入,而仅接收和客户端仅发送通过吞吐量增加到27Mbit / sec,而不是50Mbit / sec,这是以太网的一半速度,有什么帮助吗?
我同意LJ2。
为了增加吞吐量,请将缓冲区大小调整为1024字节左右,然后发送相同数量的数据; 您目前仅发送18个字节; 这不是很有效。
另外,考虑仅在一侧读取...您正在进行乒乓球匹配(客户端读取和写入之后,服务器也是如此)-如果涉及吞吐量,则无济于事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.