服务器和客户端的json数据交互(http/socket两种方式)
json
适用于现代 C++ 的 JSON。
项目地址:https://gitcode.com/gh_mirrors/js/json
免费下载资源
·
一、首先是Http方式
服务器端:
@WebServlet("/service")
public class ServiceServlet extends HttpServlet {
private static final long serialVersionUID=1L;
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException {
System.out.println("doPost方法进来");
response.setContentType("text/html");//解决中文乱码
response.setCharacterEncoding("UTF-8");
DataInputStream inputStream = null; //数据输入流
String strInputstream ="";
inputStream =new DataInputStream(request.getInputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 可以捕获内存缓冲区的数据,转换成字节数组
byte[] by = new byte[2048];
int n;
while((n=inputStream.read(by))!=-1){ //将流中的数据缓冲到字节数组中去,如果没到末尾返回的是真实个数,到末尾时,返回的是-1;
baos.write(by,0,n); //readline将会把json格式破坏掉
}
strInputstream = new String(baos.toByteArray());
inputStream.close();
baos.close();
JSONObject jsonObject=JSONObject.fromObject(strInputstream);
System.out.printf("客户端请求的数据:"+jsonObject.toString());
System.out.println("");
@SuppressWarnings("unchecked")
Map<String,Object> map=jsonObject;
Object value=0;
for(Entry<String, Object> entry:map.entrySet() ) {
value=entry.getValue();
System.out.println(entry.getKey()+"="+entry.getValue());
}
System.out.println("");
//连接数据库
Connection connection=DBUtils.getConnection();
String sql="select software_type,software_version from soft_version_info";
try {
PreparedStatement pstm=connection.prepareStatement(sql);
ResultSet rs=pstm.executeQuery();
// 获取表结构
ResultSetMetaData md = rs.getMetaData();
// 得到行的总数
int num = md.getColumnCount();
JSONArray jsonArray = new JSONArray();
while(rs.next()) {
String version = rs.getString("software_version");
JSONObject mapOfColValues = new JSONObject();
for (int i = 1; i <= num; i++) {
// 添加键值对
if((Object)rs.getObject(i)==value) {
mapOfColValues.put("server", "version");
mapOfColValues.put(md.getColumnName(i), rs.getObject(i));
mapOfColValues.put("software_version", version);
PrintWriter out=response.getWriter();
out.write(mapOfColValues.toString());
System.out.println("服务器响应的数据:"+mapOfColValues.toString());
out.flush();
out.close();
}
}
jsonArray.add(mapOfColValues);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
客户端:
public class ClientServlet{
private static String urlPath="http://localhost:8080/JsonUse/service";
public static void main(String[] args) throws IOException {
URL db=new URL(ClientServlet.urlPath);
HttpURLConnection link=(HttpURLConnection) db.openConnection();
link.setDoInput(true);
link.setDoOutput(true);
link.setRequestMethod("POST");
link.setRequestProperty("Charset", "UTF-8");
//请求
DataOutputStream dos=new DataOutputStream(link.getOutputStream());
JSONObject jsonObject=new JSONObject();
//填充json数据内容
jsonObject.put("server", "getversion");
jsonObject.put("softtype", 4);
//json转化成字符串
String string=jsonObject.toString();
//字符串转化byte数组
byte[] bytes=string.getBytes();
//发送json数据
//pWriter.write(bytes);
dos.write(bytes);
dos.flush();//刷新,向服务器发送信息;
dos.close();
//响应
//列出原始数据
StringBuilder json=new StringBuilder();
BufferedReader in=new BufferedReader(new InputStreamReader(link.getInputStream(),"UTF-8"));
String inputLine=null;
while((inputLine=in.readLine())!=null) {
json.append(inputLine);
}
in.close();
String Strjson=json.toString();
System.out.println("服务器返回的数据:");
System.out.println(Strjson.toString());
}
}
运行后服务器控制台输出:
doPost方法进来
客户端请求的数据:{"server":"getversion","softtype":4}
server=getversion
softtype=4
服务器响应的数据:{"server":"version","software_type":4,"software_version":"v1.0"}
客户端控制台输出:
服务器返回的数据:
{"server":"version","software_type":4,"software_version":"v1.0"}
二、用socket方式
服务器端:
public class Service {
public static void main(String[] args) {
try {
@SuppressWarnings("resource")
ServerSocket serverSocket=new ServerSocket(8888);//绑定端口号
System.out.println("***服务器已经打开***");//提示信息
Socket socket=null;//
//Integer count=0;
socket=serverSocket.accept();//这个socket用来读取接受的数据
DataInputStream inputStream = null; //数据输入流
// DataOutputStream outputStream = null; //数据输出流
String strInputstream ="";
inputStream =new DataInputStream(socket.getInputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 可以捕获内存缓冲区的数据,转换成字节数组
byte[] by = new byte[2048];
int n;
while((n=inputStream.read(by))!=-1){ //将流中的数据缓冲到字节数组中去,如果没到末尾返回的是真实个数,到末尾时,返回的是-1;
baos.write(by,0,n); //readline将会把json格式破坏掉
}
strInputstream = new String(baos.toByteArray());
socket.shutdownInput();
baos.close();
JSONObject jsonObject=JSONObject.fromObject(strInputstream);
//String software_version=jsonObject.optString("server");
//String software_type=jsonObject.optString("softtype");
System.out.printf("客户端请求的数据:"+jsonObject.toString());
System.out.println("");
@SuppressWarnings("unchecked")
Map<String,Object> map=jsonObject;
Object value=0;
for(Entry<String, Object> entry:map.entrySet() ) {
value=entry.getValue();
System.out.println(entry.getKey()+"="+entry.getValue());
}
// System.out.println(value);
System.out.println("");
//连接数据库
Connection connection=DBUtils.getConnection();
String sql="select software_type,software_version from soft_version_info";
PreparedStatement ptmt=connection.prepareStatement(sql);
ResultSet rs = ptmt.executeQuery();
// 获取表结构
ResultSetMetaData md = rs.getMetaData();
// 得到行的总数
int num = md.getColumnCount();
JSONArray jsonArray = new JSONArray();
while( rs.next() ){ //下移一条
//int softtype = rs.getInt("software_type"); //rs.getString( 列索引 );
String version = rs.getString("software_version");
JSONObject mapOfColValues = new JSONObject();
for (int i = 1; i <= num; i++) {
// 添加键值对
if((Object)rs.getObject(i)==value) {
mapOfColValues.put("server", "version");
mapOfColValues.put(md.getColumnName(i), rs.getObject(i));
mapOfColValues.put("software_version", version);
System.out.println("服务器响应的数据:"+mapOfColValues.toString());
}
}
jsonArray.add(mapOfColValues);
// System.out.printf( "%d, %s\r", softtype, version);
}
//服务器响应客户端
int port =socket.getPort();
System.out.printf("客户端端口号:"+port);
// Socket socket1=new Socket("localhost",port);
// OutputStream os = socket1.getOutputStream();
// PrintWriter pw =new PrintWriter(os);
//
// pw.flush();
// socket1.shutdownOutput();
// pw.close();
// os.close();
// socket1.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端:
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket=new Socket("localhost",8888);//客户端socket,用来发送数据。
OutputStream outputStream=socket.getOutputStream();
//PrintWriter pWriter=new PrintWriter(outputStream);
//创建json格式数据
JSONObject jsonObject=new JSONObject();
//填充json数据内容
jsonObject.put("server", "getversion");
jsonObject.put("softtype", 4);
//json转化成字符串
String string=jsonObject.toString();
//字符串转化byte数组
byte[] bytes=string.getBytes();
//发送json数据
//pWriter.write(bytes);
outputStream.write(bytes);
outputStream.flush();//刷新,向服务器发送信息;
//pWriter.
//pWriter.flush();
socket.shutdownOutput();
//pWriter.close();
outputStream.close();
socket.close();
int port =socket.getLocalPort();
System.out.println("客户端发送的请求数据端口:"+port);
System.out.println();
// @SuppressWarnings("resource")
// ServerSocket serverSocket=new ServerSocket(port);
//
// Socket socket1=serverSocket.accept();
//
//
// InputStream is=socket1.getInputStream();
// InputStreamReader inr =new InputStreamReader(is);
// BufferedReader bReader=new BufferedReader(inr);
// System.out.println(bReader);
// String data = bReader.readLine();
// System.out.println(data);
// while(data!=null)
// {
// System.out.println("数据是:"+data);
// data=bReader.readLine();
// }
//
// socket1.shutdownInput();
// bReader.close();
// inr.close();
// is.close();
// socket1.close();
}
}
运行后,客户端控制台输出:
客户端发送的请求数据端口:55328
服务器控制台输出:
***服务器已经打开***
客户端请求的数据:{"server":"getversion","softtype":4}
server=getversion
softtype=4
服务器响应的数据:{"server":"version","software_type":4,"software_version":"v1.0"}
客户端端口号:55328
json数据块的转化:
//创建json格式数据
JSONObject jsonObject=new JSONObject();
//填充json数据内容
jsonObject.put("server", "getversion");
jsonObject.put("softtype", 4);
//json转化成字符串
String string=jsonObject.toString();
//字符串转化byte数组
byte[] bytes=string.getBytes();
用JSONObject,需要导入几个jar包,如下:
json-lib-2.4-jdk15.jar
commons-lang-2.5.jar
commons-beanutils-1.7.0.jar
ezmorph-1.0.3.jar
commons-collections-3.1.jar
commons-logging-1.1.1.jar
需要导入到WebContent/WEB-INF/lib目录下
GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:2 个月前 )
960b763e
4 个月前
8c391e04
7 个月前
更多推荐
已为社区贡献1条内容
所有评论(0)