问题是这样,我写了一个LynnHttpClient的类,还有一个Socket的服务器类。
在LynnHttpClient类的main方法中,我使用HttpURLConnection向服务端发了一条记录。
但在服务端使用Socket读取数据的时候,为什么要读两次才能把HTTP头和内容读出来。
代码如下
客户端
public class LynnHttpClient {
public static void main(String[] args) {
try {
URL url = new URL("http://xxxxxxxx:8999/hello?name=98");//实际运行的时候,在这里进行地址替换设置
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
OutputStream out = conn.getOutputStream();
String content = "Hello World";
out.write(content.getBytes());
out.flush();
System.out.println("--------------client write finished-----------------");
int respCode = conn.getResponseCode();
System.out.println("----------server response code:" + respCode + "-------------------------");
} catch (Exception e) {
e.printStackTrace();
}
}
}
服务端
public class HttpServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(8999));
Socket socket = serverSocket.accept();
socket.setKeepAlive(true);
InputStream input = socket.getInputStream();
int readCount = 0;
while (true) {
StringBuilder strBuilder = new StringBuilder();
byte[] buffer = new byte[1024];
int readBytes = -1;
do {
readBytes = input.read(buffer);
readCount++;
if (readBytes > 0) {
String bufferStr = new String(buffer, 0, readBytes);
strBuilder.append(bufferStr);
System.out.println("------------the content read for count " + readCount + "-----------------");
System.out.println(bufferStr);
}
} while (readBytes != -1);
System.out.println(strBuilder.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行的结果如下
client输出
server输出
我的问题是:
server端的输出为什么不是这样的?
------------the content read for count 1-----------------
POST /hello?name=98 HTTP/1.1
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.6.0_45
Host: 10.94.26.107:8999
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-type: application/x-www-form-urlencoded
Content-Length: 11
Hello World
服务器在读数据的时候,这些数据不是都已经发送到服务端了么,为什么无法一次读出来?