很多了解了Socket和Servlet的内容的家人们,可能想让Socket和Servlet也进行一下通信,可以完全可以,因为二者都是可以基于http协议来发送接收数据。
那些部署Tomcat,创建Servlet程序,配置Web.xml的内容在这就忽略了,不懂得家人们,可以百度去b站看看,很简单,此外学习此章节还需要知道io流的一些内容!
在这就直接上代码了,首先我创建了一个普通的java项目,里面写了两个类,一个发送get方法的Socket类,另一个是发送post方法的Socket的类。
ClientSocket.java(get方法)代码如下:
package com.socket.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSocket {
public static void main(String[] args) throws Exception, IOException {
// TODO Auto-generated method stub
Socket socket = new Socket("127.0.0.1", 8080);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// 发送数据的格式,注意url要自己定义!!不能按照我的来!
String url = "GET /WebTest07/socket?get1=123&get2=456 HTTP/1.1\r\n" + "Host:localhost:8080\r\n" + "\r\n";
out.write(url.getBytes());
// 接受Servlet发送过来的数据
byte[] b = new byte[1024];
int count = in.read(b);
while (count != -1) {
System.out.println("Servlet响应过来的信息:" + new String(b, 0, count));
count = in.read(b);
}
socket.close();
}
}
ClientSocketPost.java(post方法)代码如下:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URLEncoder;
import java.net.UnknownHostException;
public class ClientSocketPost {
public static void main(String[] args) throws Exception, IOException {
// TODO Auto-generated method stub
Socket socket = new Socket("127.0.0.1", 8080);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// POST数据 发送的数据的格式时,必须要定义发送的格式
// Content-Type: application/x-www-form-urlencoded
// Content-Length:23
String form = "username=zhangsan&password=123";
String url = "POST /WebTest07/socket HTTP/1.1\r\n"
+ "Host:localhost:8080\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length:30\r\n"
+ "\r\n" + form;
out.write(url.getBytes());
out.flush();
// 接受Servlet发送过来的数据
byte[] b = new byte[1024];
int count = in.read(b);
while (count != -1) {
System.out.println("Servlet响应过来的信息:" + new String(b, 0, count));
count = in.read(b);
}
socket.close();
}
}
设置好上面的类,我们就设置Servlet程序内部的类,我直接创建了一个SocketTestServer类作为服务器来接受,注意别忘记配置Web.xml的内容。
SocketTestServer.java(Servlet服务器的java类) 代码如下:
两个方法doget和dopost方法一个处理get请求,一个处理post请求。
package com.socket.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SocketTestServer extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("get -- Socket已经访问过");
response.setContentType("text/html; charset=utf-8");
InputStream in = request.getInputStream();
OutputStream out = response.getOutputStream();
String str1 = request.getParameter("username");
String str2 = request.getParameter("password");
System.out.println("客户端发送过来的参数值为:" + str1);
System.out.println("客户端发送过来的参数值为:" + str2);
// 像Socket客户端发送数据
String str = "我是Servlet,你可以发表演讲了";
out.write(str.getBytes());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("post -- Socket已经访问过");
response.setContentType("text/html;charset=UTF-8");
String str2 = request.getParameter("username");
String str3 = request.getParameter("password");
System.out.println("username为:" + str2);
System.out.println("password为:" + str3);
// 需要注意我们获取到的http协议内容全部存储到了request中,因此我们没必要再进行一个获取操作,如果再进行一个获取操作参数什么的也都是null而已。
// InputStream in = request.getInputStream();
// OutputStream out = response.getOutputStream();
System.out.println("方法名:" + request.getMethod());
System.out.println("ContentType类型:" + request.getContentType());
System.out.println("ContentLength值为:" + request.getContentLength());
PrintWriter writer = response.getWriter();
writer.write("ok");
}
}
Web.xml配置如下:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>WebTest07display-name>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
<welcome-file>index.htmwelcome-file>
<welcome-file>index.jspwelcome-file>
<welcome-file>default.htmlwelcome-file>
<welcome-file>default.htmwelcome-file>
<welcome-file>default.jspwelcome-file>
welcome-file-list>
<servlet>
<description>description>
<display-name>SocketTestServerdisplay-name>
<servlet-name>SocketTestServerservlet-name>
<servlet-class>com.socket.test.SocketTestServerservlet-class>
servlet>
<servlet-mapping>
<servlet-name>SocketTestServerservlet-name>
<url-pattern>/socketurl-pattern>
servlet-mapping>
web-app>
完成上面步骤我们,将Servlet工程放到Tomcat中,随后启动Tomcat。
启动Tomcat后,我们就可以来测试了,分别启动ClientSocket类和ClientSocketPost类,来测试get和post的http协议接受响应,查看控制台信息就完成了。