Socket通信Des加密笔记Word格式文档下载.docx
- 文档编号:17553351
- 上传时间:2022-12-07
- 格式:DOCX
- 页数:53
- 大小:31.22KB
Socket通信Des加密笔记Word格式文档下载.docx
《Socket通信Des加密笔记Word格式文档下载.docx》由会员分享,可在线阅读,更多相关《Socket通信Des加密笔记Word格式文档下载.docx(53页珍藏版)》请在冰豆网上搜索。
服务器端套接字并不定位具体的客户端套接字,而是处于等待连接的状态,实时监控网络状态,等待客户端的连接请求。
III.客户端请求
指客户端的套接字提出连接请求,要连接的目标是服务器端的套接字。
为此,客户端的套接字必须首先描述它要连接的服务器的套接字,指出服务器端套接字的地址和端口号,然后就向服务器端套接字提出连接请求。
IV.连接确认
当服务器端套接字监听到或者说接收到客户端套接字的连接请求时,就响应客户端套接字的请求,建立一个新的线程,把服务器端套接字的描述发给客户端,一旦客户端确认了此描述,双方就正式建立连接。
而服务器端套接字继续处于监听状态,继续接收其他客户端套接字的连接请求。
1.1.3通信实例
I.Java服务端代码:
importjava.io.IOException;
import.InetSocketAddress;
import.UnknownHostException;
importjava.nio.ByteBuffer;
importjava.nio.CharBuffer;
importjava.nio.channels.SelectionKey;
importjava.nio.channels.Selector;
importjava.nio.channels.ServerSocketChannel;
importjava.nio.channels.SocketChannel;
importjava.nio.charset.Charset;
importjava.nio.charset.CharsetDecoder;
importjava.util.Collection;
importjava.util.Hashtable;
importjava.util.Iterator;
importjava.util.Set;
publicclassMsgServer{
publicSelectorsel=null;
publicServerSocketChannelserver=null;
publicSocketChannelsocket=null;
publicintthisport=4900;
privateStringresult=null;
privateHashtable<
String,SocketChannel>
userlists;
privateSocketChannelreadingsocket=null;
publicMsgServer(){
System.out.println("
Insidestartserver"
);
}
publicMsgServer(intport){
thisport=port;
publicvoidinit()throwsIOException,UnknownHostException{
Insideinitialization"
sel=Selector.open();
server=ServerSocketChannel.open();
server.configureBlocking(false);
InetSocketAddressisa=newInetSocketAddress("
192.85.1.235"
thisport);
server.socket().bind(isa);
userlists=newHashtable<
();
publicvoidstartServer()throwsIOException
{
init();
server.register(sel,SelectionKey.OP_ACCEPT);
while(sel.select()>
0)
{
Set<
?
>
readyKeys=sel.selectedKeys();
Iterator<
it=readyKeys.iterator();
while(it.hasNext())
SelectionKeysk=(SelectionKey)it.next();
it.remove();
if(sk.isAcceptable())
ServerSocketChannelssc=(ServerSocketChannel)sk.channel();
socket=(SocketChannel)ssc.accept();
System.out.println(socket.toString());
/*设置为非阻塞模式*/
socket.configureBlocking(false);
Stringsocketname=socket.socket().getRemoteSocketAddress().toString();
socket.register(sel,SelectionKey.OP_READ);
sk.interestOps(SelectionKey.OP_ACCEPT);
userlists.put(socketname,socket);
System.out.println(socketname+"
已经连接了!
!
"
if(sk.isReadable())
startwrite..."
readingsocket=(SocketChannel)sk.channel();
Stringret=readMessage(readingsocket);
if(ret.equalsIgnoreCase("
@@@@@hasleft!
))
sk.cancel();
readingsocket.close();
userlists.remove(readingsocket.socket().getRemoteSocketAddress().toString());
System.out.println("
leftmessage:
+ret.replace("
@@@@@"
readingsocket.socket().getRemoteSocketAddress().toString()));
sendMessage(ret.replace("
elseif(ret.length()>
0)
//sk.cancel();
sendservermsg:
+ret);
//传回信息
sendMessage(ret);
publicvoidsendMessage(Stringmsg)throwsIOException{
ByteBufferbuffer=ByteBuffer.allocate(1024);
buffer=ByteBuffer.wrap(msg.getBytes());
//ByteBufferbuffer=ByteBuffer.wrap(msg.getBytes("
UTF-8"
));
Collection<
SocketChannel>
channels=userlists.values();
SocketChannelsc;
for(Objecto:
channels){
sc=(SocketChannel)o;
sc.write(buffer);
buffer.flip();
try{
Thread.sleep(500);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
publicStringreadMessage(SocketChannelsc){
ByteBufferbuf=ByteBuffer.allocate(1024);
try{
sc.read(buf);
buf.flip();
Charsetcharset=Charset.forName("
utf-8"
CharsetDecoderdecoder=charset.newDecoder();
CharBuffercharBuffer=decoder.decode(buf);
result=charBuffer.toString();
System.out.println(result);
}catch(IOExceptione){
result="
;
returnresult;
publicstaticvoidmain(Stringargs[]){
MsgServerms=newMsgServer();
ms.startServer();
e.printStackTrace();
System.exit(-1);
}
II.Android客户端代码:
(1)客户端(android)Activity:
importandroid.app.Activity;
importandroid.content.Intent;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.Button;
importandroid.widget.EditText;
publicclassMsgClientextendsActivity
{
/**阻塞Socket客户端*/
privateEditTextedt;
publicvoidonCreate(BundlesavedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edt=(EditText)this.findViewById(R.id.edt);
Buttonbut=(Button)this.findViewById(R.id.Button);
but.setOnClickListener(newView.OnClickListener(){
@Override
publicvoidonClick(Viewv)
{
//TODOAuto-generatedmethodstub
Intentintent=newIntent(MsgClient.this,ReceiveMessage.class);
Stringmsg=edt.getText().toString();
intent.putExtra("
msg"
msg);
//启动服务
MsgClient.this.startService(intent);
});
(2)客户端(android)Socket连接类:
importjava.nio.charset.CharacterCodingException;
importandroid.app.Notification;
importandroid.app.NotificationManager;
importandroid.app.PendingIntent;
importandroid.app.Service;
importandroid.content.Context;
importandroid.os.Binder;
importandroid.os.IBinder;
importandroid.widget.Toast;
publicclassReceiveMessageextendsService{
privateSocketChannelclient=null;
privateInetSocketAddressisa=null;
privateintNOTIFICATION=R.string.local_service_connected;
//privateStringmsg="
publicvoidonCreate()
super.onCreate();
ConnectToServer();
StartServerListener();
publicvoidonDestroy()
super.onDestroy();
DisConnectToServer();
publicvoidonStart(Intentintent,intstartId)
super.onStart(intent,startId);
Stringmsg=intent.getStringExtra("
if(msg.length()>
0)
{
SendMessageToServer(msg);
messageiscomming:
+msg);
privatevoidStartServerListener(){
//TODOAuto-generatedmethodstub
ServerListenera=newServerListener();
a.start();
//链接服务端
publicvoidConnectToServer()
try{
client=SocketChannel.open();
isa=newInetSocketAddress("
4900);
client.connect(isa);
//client.configureBlocking(false);
catch(IOExceptione)
//断开服务端
privatevoidDisConnectToServer(){
try
client.close();
catch(IOExceptione){e.printStackTrace();
publicIBinderonBind(Intentintent){
//Stringmsg=intent.getStringExtra("
//System.out.println("
绑定的数据"
returnmBinder;
publicclassLocalBinderextendsBinder
ReceiveMessagegetService()
returnReceiveMessage.this;
privatefinalIBindermBinder=newLocalBinder();
privatevoidSendMessageToServer(Stringmsg2)
ByteBufferbytebuf=ByteBuffer.allocate(1024);
bytebuf=ByteBuffer.wrap(msg2.getBytes("
client.write(bytebuf);
bytebuf.flip();
publicvoidshownotification(Stringtab)
NotificationManagerbarmanager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notificationmsg2=newNotification(android.R.drawable.stat_notify_chat,"
信息"
System.currentTimeMillis());
PendingIntentcontentIntent=PendingIntent.getActivity(this,0,newIntent(this,MsgClient.class),PendingIntent.FLAG_ONE_SHOT);
服务器端发回信息了信息:
+contentIntent);
msg2.setLatestEventInfo(this,"
服务器端发回信息了"
"
信息:
+tab,contentIntent);
barmanager.notify(NOTIFICATION,msg2);
//Toast.makeText(ReceiveMessage.this,tab,Toast.LENGTH_SHORT).show();
//System.out.println(tab);
publicclassServerListenerextendsThread
publicvoidrun()
try
while(true)
{
ByteBufferbuf=ByteBuffer.allocate(1024);
client.read(buf);
buf.flip();
Charsetcharset=Charset.forName("
CharsetDecoderdecoder=charset.newDecoder();
CharBuffercharbuffer;
charbuffer=decoder.decode(buf);
Stringresult=charbuffer.toString();
if(result.length()>
{
//System.out.println("
result"
+"
%%%%%%%%%5555"
+result);
shownotification(result);
}
}
catch(CharacterCodingExceptione)
catch(IOExceptione)
(1)服务端必须先与客户端运行,才能通信
(2)客户端和服务端所使用的编码方式要相同,否则会出现乱码问题。
1.2Des之CBC加密解密
1.2.1DES简单介绍
I.DES是一种第一次解密算法
对称加密算法就是能将数据加解密。
加密的时候用密钥对数据进行加密,解密的时候使用同样的密钥对数据进行解密。
II.交互模型
(1)消息传递双方约定密钥,通常由消息发送方(甲方)构建密钥通
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Socket 通信 Des 加密 笔记