HttpClient模拟IE浏览器 ServerSocket模拟服务器的例子
httpclient模拟浏览器调用serversocket的代码:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://127.0.0.1:9999");
httpGet.addHeader("Accept","text/html, application/xhtml+xml, */*");
httpGet.addHeader("Accept-Language","zh-CN,en-US;q=0.5");
httpGet.addHeader("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
httpGet.addHeader("Accept-Encoding","gzip, deflate");
httpGet.addHeader("Host","localhost:9999");
httpGet.addHeader("Connection","Keep-Alive");
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream inputStream = httpResponse.getEntity().getContent();
System.err.println("从服务器端获取的内容为:" + EntityUtils.toString(httpResponse.getEntity()));
serverSocket模拟服务器端:
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9999);
System.err.println("服务器已启动...............");
while (true) {
Socket socket = serverSocket.accept();
if (socket != null) {
System.err.println("客户端已连接IP地址为:" + socket.getInetAddress());
//封装输出流
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
//封装输入流
BufferedReader fBufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("d:\\a.txt"))));
String fileContent = fBufferedReader.readLine();
bufferedWriter.write(fileContent);
bufferedWriter.flush();
}
socket.close();
}
}
server端将读取d:\a.txt文件的内容写到返回留中
现在的问题是:
server端启动后,执行客户端调用代码,serverSocket.accept()方法成立,得到socket.但是将读取的文件内容写到socket的输出流后,client端没有任何反应,一直是在等待。socket端又再次的进行下一个socket连接进来的等待。关于文件的读取通过debug发现是没有任何问题的,也可以正常的写入到输出流。
有用过的哥们 麻烦帮解决一下
------解决方案--------------------
呃。。。还真没有啥资料。
基本上基于自己对HTTP协议的理解,然后再判断这个能力是否应该有,接着Google看有无样例。
如果最后找不到,就自己写个包装类来实现。