TCP传输中使用AES加密和gizp压缩(2)--封装TcpUtil,封装后实现登陆

一、TcpUtil
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/**
*@authorqiwenming
*@time2015年5月31日上午4:24:02
*@说明TcpUtil
*/
publicclassTcpUtil{
privateOutputStreamoutputStream;
privateInputStreaminputStream;
privateSocketsocket;
privateProgressDialogpd;//进度提示框
privateStringTAG=TcpUtil.class.getName();
/**
*实体类转为json
*
*@parambeanClass
*@return
*/
public<T>StringgetSendData(TbeanClass){
if(beanClass==null){
return"";
}
Tbean=beanClass;
Gsongson=newGson();
Stringstr=gson.toJson(bean);
returnstr;
}
/**
*拼接请求字符串
*
*@parambeanClass
*@paramserverName
*@return
*/
public<T>StringgetRequestString(TbeanClass,StringserverName){
StringBuildersb=newStringBuilder();
sb.append("{");
//header拼装
sb.append("\"header\":{");
sb.append("\"service_name\":\""+serverName+"\"");
sb.append("},");
//body拼装
sb.append("\"body\":");
sb.append(getSendData(beanClass));
sb.append("}");
returnsb.toString();
}
/**
*@paramcontext
*@paramMessage
*提示框信息
*@paramisShowDialog
*是否显示提示框
*@paramcallBack
*回调
*@parambeanClass
*@paramserviceName
*调用的服务器名
*/
public<T>voidrequestData(finalContextcontext,finalStringmessage,
booleanisShowDialog,finalTcpRequsetCallBackcallBack,
TbeanClass,StringserviceName){
//创建一个AsyncTask去这行请求为什么
newMyTast<T>(context,message,isShowDialog,callBack,beanClass,serviceName).execute("");
}
/**
*发送请求数据
*
*@paramrequestStr
*请求数据
*@throwsException
*异常
*/
publicvoidsend(StringrequestStr)throwsException{
if(outputStream==null){
outputStream=socket.getOutputStream();
}
//编码
byte[]encryptBytes=AESUtil.encrypt(requestStr.getBytes());
//压缩
byte[]compressBytes=GZipUtils.compress(encryptBytes);
//写入数据流操作
DataOutputStreamdos=newDataOutputStream(outputStream);
dos.writeInt(compressBytes.length);
dos.write(compressBytes);
}
/**
*接收数据
*
*@return服务器返回的字符数据
*@throwsException
*/
publicStringreceive()throwsException{
if(inputStream==null){
inputStream=socket.getInputStream();
}
//获取输入流读取服务端传递过来的流
DataInputStreamdin=newDataInputStream(inputStream);
intavailableLen=din.readInt();//阻塞方法
byte[]data=receiveBytes(din,availableLen);//读取字节数据
byte[]uncompress=GZipUtils.decompress(data);
byte[]decrypt=AESUtil.decrypt(uncompress);
returnnewString(decrypt,"UTF-8");
}
/**
*得到接收的byte数组数据
*
*@paramis
*输入流(服务端传递过来的数据)
*@paramlength
*读取的长度
*@return字节数组
*@throwsIOException
*/
privatebyte[]receiveBytes(InputStreamis,intlength)throwsIOException{
inttmpLength=1024;//每次读取最大缓冲区大小
byte[]ret=newbyte[length];
intreaded=0,offset=0,left=length;
byte[]bs=newbyte[tmpLength];
while(left>0){
try{
//读取数据到bs数据中,读取的长度返回到readed中
readed=is.read(bs,0,Math.min(tmpLength,left));
if(readed==-1)//读取结束
break;
System.arraycopy(bs,0,ret,offset,readed);//copy数据
}finally{
offset+=readed;//更新读取的位置
left-=readed;//读取的长度减小
}
}
returnret;
}
/**
*关闭流
*
*@throwsIOException
*/
publicvoiddisconnect()throwsIOException{
if(outputStream!=null){
outputStream.close();
}
if(inputStream!=null){
inputStream.close();
}
if(socket!=null&&!socket.isClosed()){
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
}
}
/**
*@authorqiwenming
*@param<T>
*@creation2015-5-19下午3:39:56
*@instruction网络请求(参数,进度,结果)
*/
classMyTast<T>extendsAsyncTask<String,Integer,NetResponse>{
privateContextcontext;
privateStringmessage;
privatebooleanisShowDialog;
privateTcpRequsetCallBackcallBack;
privateTbeanClass;
privateStringserviceName;
publicMyTast(finalContextcontext,finalStringmessage,
booleanisShowDialog,TcpRequsetCallBackcallBack,TbeanClass,
StringserviceName){
this.context=context;
this.message=message;
this.isShowDialog=isShowDialog;
this.callBack=callBack;
this.beanClass=beanClass;
this.serviceName=serviceName;
}
/**
*请求数据前
*/
protectedvoidonPreExecute(){
if(!ConnectUtils.isNetworkConnected(context)){
Toast.makeText(context,"网络未连接,请检查网络",0).show();
return;
}
if(isShowDialog){//判断是否需要显示dialog
pd=newProgressDialog(context);
if(this.message==null){//判断要显示的文字
pd.setMessage("正在加载数据");
}else{
pd.setMessage(message);
}
pd.show();
}
}
/**
*请求数据中
*/
protectedNetResponsedoInBackground(String...params){
NetResponsenrp=newNetResponse();
try{
socket=newSocket("192.168.1.106",8888);
socket.setSoTimeout(10*1000);
//这里不使用params使用他会加[]所以不用
StringrequestMsg=getRequestString(beanClass,serviceName);
if(MyApplication.isShowLog){//如果需要打印日志的话打印数据
Log.i(serviceName,"请求数据###"+requestMsg);
}
send(requestMsg);
StringrespMsg=receive();//接收数据
nrp.status=ResponseStatus.OK;
nrp.responseMsg=respMsg;
if(MyApplication.isShowLog){//如果需要打印日志的话打印数据
Log.i(serviceName,"响应数据"+respMsg);
}
}catch(IOExceptione){
nrp.status=ResponseStatus.ERR;
nrp.responseMsg=TAG+"---doInBackground():IOException:请求或者接收数据时候出问题";
nrp.exception=e;
//e.printStackTrace();
}catch(Exceptione){
nrp.status=ResponseStatus.ERR;
nrp.responseMsg=TAG+"---doInBackground():IOException:请求或者接收数据时候出问题";
nrp.exception=e;
//e.printStackTrace();
}finally{
//关闭对话框
if(pd!=null&&pd.isShowing()){
pd.dismiss();
}
try{
if(socket!=null&&!socket.isClosed()){
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket=null;
}
if(outputStream!=null){
outputStream.close();
}
if(inputStream!=null){
inputStream.close();
}
}catch(IOExceptione){
//关闭流除了问题
//e.printStackTrace();
nrp.status=ResponseStatus.ERR;
nrp.responseMsg=TAG+"---doInBackground():IOException:关闭流除了问题";
nrp.exception=e;
// callBack.onErr(nrp);
}
}
returnnrp;
}
/**
*请求数据结束后
*/
protectedvoidonPostExecute(NetResponseresult){
if(ResponseStatus.OK==result.status){//请求成功
callBack.onRequestSuccess(result.responseMsg);
}else{//请求失败
callBack.onErr(result);
}
}
}
}

TcpRequsetCallBack
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
*@authorqiwenming
*@time2015年5月30日下午11:35:41
*@说明Tcp请求的回调类
*/
publicabstractclassTcpRequsetCallBack<TR>{
// privateBaseRspBean<TR>baseRsp;
privateClass<TR>beanClass;
privateStringTAG=TcpRequsetCallBack.class.getName();
/**
*构造函数
*@param<TR>
*@parambeanClass
*/
publicTcpRequsetCallBack(Class<TR>beanClass){
this.beanClass=beanClass;
}
/**
*请求成功的方法
*@paramresponseMsg
*/
public<T>voidonRequestSuccess(StringresponseMsg){
Gsongson=newGson();
try{
TRbean=gson.fromJson(responseMsg,beanClass);
if(beaninstanceofBaseRespBean){
BaseRespBeanbnBean=(BaseRespBean)bean;
if(!"0000".equals(bnBean.result_code)){//这里的判断根据规定的响应码来判断
onfail(bnBean.result_code,bnBean.result_msg);
return;
}
onSuccess(bean);
}
}catch(JsonSyntaxExceptione){
NetResponsenetRspJson=newNetResponse();
netRspJson.exception=e;
netRspJson.responseMsg=TAG+":onRequestSuccess():JsonSyntaxException:响应数据转换json的时候处理问题";
onErr(netRspJson);
}
};
/**
*得到正确的数据
*@paramheader
*@paramresultMsg
*@paramresultCode
*/
publicabstractvoidonSuccess(TRbean);
/**
*数据错误
*@paramfailDesc错误信息
*@paramresult_code错误码
*/
publicvoidonfail(Stringresult_code,StringfailDesc){
Log.e(TAG+".onfail","请求数据失败:result_code:"+result_code+"failDesc:"+failDesc);
};
/**
*请求报错
*@paramnetQuest
*/
publicvoidonErr(NetResponsenetRsp){
Log.e(TAG+".onErr",netRsp.responseMsg);
netRsp.exception.printStackTrace();
};
}

BaseRespBean
1
2
3
4
5
6
7
8
9
/**
*@authorqiwenming
*@time2015年5月31日上午12:11:18
*@说明响应基类
*/
public class BaseRespBean implements Serializable{
public Stringresult_code;
public Stringresult_msg;
}


二、登陆中客户端重要涉及的类
1.LoginReqBean
1
2
3
4
5
6
7
8
9
/**
*@authorqiwenming
*@time2015年5月30日下午11:57:40
*@说明登陸請求的javabean
*/
public class LoginReqBean implements Serializable{
public Stringusername;
public Stringpassword;
}
2.BaseRespBean
1
2
3
4
5
6
7
8
9
/**
*@authorqiwenming
*@time2015年5月31日上午12:11:18
*@说明响应基类
*/
public class BaseRespBean implements Serializable{
public Stringresult_code;
public Stringresult_msg;
}
3.LoginRespBean
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
*@authorqiwenming
*@time2015年5月31日上午12:10:41
*@说明登陆响应类
*/
public class LoginRespBean extends BaseRespBean{
public LoginDatadata;
public class LoginData implements Serializable{
public StringnickName;
public int age;
}
}
三、登陆中客户端登陆方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
*登陆
*
*@paramv
*/
public void toLogin(Viewv){
Stringname=nameEdt.getText().toString().trim();
Stringpwd=pwdEdt.getText().toString().trim();
if ( "" .equals(name)){
Toast.makeText( this , "用户名为空" , 0 ).show();
return ;
}
if ( "" .equals(name)){
Toast.makeText( this , "密码为空" , 0 ).show();
return ;
}
LoginReqBeanbean= new LoginReqBean();
bean.username=name;
bean.password=pwd;
new TcpUtil().requestData( this , "登陆请求中..." , true ,
new TcpRequsetCallBack<LoginRespBean>(LoginRespBean. class ){
@Override
public void onSuccess(LoginRespBeanbean){
//登陆成功
Intenti= new Intent(MainActivity. this ,HomeActivity. class );
i.putExtra( "loginbean" ,bean);
startActivity(i);
MainActivity. this .finish();
}
@Override
public void onfail(Stringresult_code,StringfailDesc){
//登陆失败
super .onfail(result_code,failDesc);
Toast.makeText(MainActivity. this ,result_code+ ":" +failDesc, 0 ).show();
}
},bean, "loginServer" );
}

四、java控制台程序模拟的后台主要方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/**
*@authorxiaoming
*@time2015年5月30日下午5:01:01
*@说明AesDemo
*/
public class AesDemo{
public static void main(String[]args){
test();
}
public static void test(){
ServerSocketss= null ;
try {
ss= new ServerSocket( 8888 );
while ( true ){
final Sockets=ss.accept();
new Thread( new Runnable(){
public void run(){
try {
DataInputStreamdis= new DataInputStream(
s.getInputStream());
//读取数据
byte []recData=( new TcpUtil()).readData(dis);
System.out.println( "长度:" +recData.length);
解压缩
byte []uncompress=GZipUtils.decompress(recData);
//解密
byte []decrypt=AESUtil.decrypt(uncompress);
//======================响应部分================================
DataOutputStreamdos= new DataOutputStream(
s.getOutputStream());
byte []respData=handlerData(decrypt);
//加密
byte []encrypt=AESUtil.encrypt(respData);
压缩
byte []compress=GZipUtils.compress(encrypt);
dos.writeInt(compress.length); //把数据的长度写过去
dos.write(compress);
dos.flush();
s.shutdownOutput();
} catch (InvalidCipherTextExceptione){
e.printStackTrace();
} catch (IOExceptione){
e.printStackTrace();
} catch (Exceptione){
e.printStackTrace();
}
}
}).start();
}
} catch (Exceptione){
e.printStackTrace();
} finally {
try {
//关闭资源
if (ss!= null ){
ss.close();
}
} catch (IOExceptione){
e.printStackTrace();
}
}
}
/**
*实体类转为json
*
*@parambeanClass
*@return
*/
public static <T>StringgetSendData(TbeanClass){
if (beanClass== null ){
return "" ;
}
Tbean=beanClass;
Gsongson= new Gson();
Stringstr=gson.toJson(bean);
return str;
}
/**
*处理数据
*/
public static byte []handlerData( byte []decrypt){
StringreqMsg= new String(decrypt);
System.out.println( "请求的数据:" +reqMsg);
Gsongson= new Gson();
//获得数据
LoginReqBeanbean=gson.fromJson(reqMsg,LoginReqBean. class );
LoginRespBeanrespBean= new LoginRespBean();
if ( null !=bean){
if ( "loginServer" .equals(bean.header.service_name)){
if ( "xiaoming" .equals(bean.body.username)){
if ( "520" .equals(bean.body.password)){
respBean.result_code= "0000" ;
respBean.result_msg= "登陆成功" ;
respBean.data.nickName= "小明" ;
respBean.data.age= 24 ;
} else {
respBean.data= null ;
respBean.result_code= "1001" ;
respBean.result_msg= "密码错误" ;
}
} else {
respBean.data= null ;
respBean.result_code= "1002" ;
respBean.result_msg= "用户名错误" ;
}
} else {
respBean.data= null ;
respBean.result_code= "1003" ;
respBean.result_msg= "没有这个服务名" ;
}
} else {
respBean.data= null ;
respBean.result_code= "1004" ;
respBean.result_msg= "数据为空" ;
}
StringrespMsg=getSendData(respBean);
System.out.println( "响应的数据:" +respMsg);
return respMsg.getBytes();
}
}

五、主要效果







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值