因為socket是雙向的通信,所以我們采用兩個密碼。加密輸出的數(shù)據(jù)并解密輸入的數(shù)據(jù)。我們使用getInputStream()和 getOutputStream(),這兩種方法來加密合解密通用的輸入和輸出的經(jīng)過包裝的數(shù)據(jù)流。見 表 D 。
listen方法用來監(jiān)聽socket 。
int aByte;
while ((aByte = in.read()) >;= 0) {
system.out.println((char)aByte);
}
Socket 客戶
現(xiàn)在我們來看看客戶端。見 表 G ?蛻舳说墓ぷ骱头⻊掌鞫撕芟嗨,只是反過來了。首先,我們創(chuàng)立一個套接字連接到服務器。使用KeyGen 找到關鍵字,創(chuàng)立一個安全套接字(SecretSocket)。然后我們利用它的OutputStream給服務器發(fā)送數(shù)據(jù):
Key key = KeyGen.getSecretKey();
Socket s = new Socket("localhost", 4444);
SecretSocket ss = new SecretSocket(s, key);
OutputStream os = ss.getOutputStream();
os.write("Hello World!".getBytes());
os.flush();
os.close();
s.close();