[color=red]ServerSocket模拟服务器端[/color]
[color=red]httpclient模拟浏览器调用server端[/color]
public class ServerSocketModel{
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务器已启动...............");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("客户端已连接IP地址为:" + socket.getInetAddress());
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readContent;
while ((readContent = bufferedReader.readLine()) != null) {
System.out.println("ReadFromClient: " + readContent);
if (readContent.length() == 0)
break;
}
//封装输出流
OutputStream outputStream = socket.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
//封装输入流
System.out.println("读取完毕,准备输出返回信息.");
bufferedWriter.write("HTTP/1.1 200 OK\n");
bufferedWriter.write("Content-Length: 10\n");
bufferedWriter.write("Content-Type: text/html;charset=utf8\n");
bufferedWriter.write("\n"); // 区分HEAD区和正文区
bufferedWriter.write("1234567890");
System.out.println("返回信息输出完毕.");
bufferedWriter.flush();
socket.close();
System.out.println("客户端连接已释放.");
}
}
}
[color=red]httpclient模拟浏览器调用server端[/color]
public class HttpClientModel {
public static void main(String[] args) {
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()));
}
}