客户端用socket连接web服务器发送HTTP请求,访问一个Servlet /service .并接收servlet的相应数据
我的客户端可以连接上服务端,但是发送的消息Servlet接收不到,Servlet发送回的消息客户端也接收不到。
客户端:
- Java code
public class Client {
public static void main(String[] arg) {
Socket socket;
try {
socket = new Socket("10.20.64.203", 7001);
OutputStream os = socket.getOutputStream();
InputStream ins = socket.getInputStream();
String data= getXmlString();
StringBuffer sb = new StringBuffer();
sb.append("POST /service HTTP/1.1\r\n");// 注意\r\n为回车换行
sb.append("Accept-Language: zh-cn\r\n");
sb.append("Connection: Keep-Alive\r\n");
sb.append("Host:localhost\r\n");
sb.append("Content-Length:11\r\n");
sb.append("\r\n");
sb.append("data=abc\r\n");
sb.append("\r\n");
// 接收Web服务器返回HTTP响应包
os.write(sb.toString().getBytes());
os.flush();
byte[] b = new byte[1000];
ins.read(b); //读取http头
InputStreamReader ireader = new InputStreamReader(ins);
java.io.BufferedReader reader = new java.io.BufferedReader(ireader);
String s = null;//读取内容
System.out.println( "response:");
while(( s= reader.readLine())!= null){//读取不到内容?
System.out.println(s);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Servlet
- Java code
public class ProcessServlet extends HttpServlet { private static final long serialVersionUID = 1L; public ProcessServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("receive Request message*******************:"); PrintWriter out = response.getWriter(); response.setContentType("text/html;charset=utf-8"); out.println("<html>"); out.println("<head><title>First servlet</title></head>"); out.println("<body>"); out.println("welcome use selevet"); out.println("</body>"); out.println("</html>"); BufferedReader reader = request.getReader(); String msg = null; while ((msg = reader.readLine()) != null) { System.out.println("receive Request message:" + msg); String send = "HTTP/1.1 200 OK\r\n" + "Filename: " + "\r\n" + "Content_length: " + "\r\n"; out.println(send); out.flush(); } out.flush(); out.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }}