I'm writting a java class that tests uploading speed connection to a server. I want to check how many data can be send in 5 seconds.
I've written a class which creates a URL, creates a connection, and sends data trough the outPutStream. There is a loop where I writt开发者_Python百科e data to the stream for 5 seconds. However I'm not able to see when data has been send (I writte data to the output stream, but data is not send yet). How can I wait untill data is really sent to the server? Here goes my code (which does not work):
URL u = new URL(url)
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
uc.setDoOutput(true);
uc.setDoInput(true);
uc.setUseCaches(false);
uc.setDefaultUseCaches(false);
uc.setRequestMethod("POST");
uc.setRequestProperty("Content-Type", "application/octet-stream");
uc.connect();
st.start();
// Send the request
OutputStream os = uc.getOutputStream();
//This while is incorrect cause it does not wait for data beeing sent
while (st.getElapsedTime() < miliSeconds) {
os.write(buffer);
os.flush();
st.addSize(buffer.length);
}
os.close();
Thanks
By default, the whole output stream is buffered in memory before being sent. You need to enable chunked streaming mode or fixed length streaming mode so that the output stream is being written directly without buffered.
Here, add
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
uc.setChunkedStreamingMode(8192); // <-- enable chunked streaming mode before connecting to server.
If you want to measure the real network speed you have you should not do it over HTTP because you will not take in account the overhead of the protocol. What you need is a real client/server solution in raw TCP/IP. Your server listen on a socket and you send unbuffered data to it. Then you can make your measures client AND server side and compare them.
精彩评论