//這裏的公開,是要求服務器發送公鑰到客戶客戶端從服務器請求
package gameserver;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import java.net.Socket;
import java.io.*;
import javax.swing.JFrame;
import java.awt.*;
import javax.swing.*;
public class GameClient extends JFrame implements ActionListener {
private JButton b1 = new JButton("press");
public GameClient() {
GridLayout layout = new GridLayout(3, 0, 0, 0);
setLayout(layout);
setSize(320,150);
add(b1);
b1.addActionListener(this);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
GameClient frame = new GameClient();
frame.setVisible(true);
}
});
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) {
Socket socket = null;
ObjectInputStream in = null;
ObjectOutputStream out = null;
Scanner console = new Scanner(System.in);
try {
socket = new Socket("127.0.0.1", 12346);
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
Object result;
result = in.readObject();
System.out.println(result);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
}
//服務器代碼,公鑰發送給客戶端時,客戶端連接
代碼package gameserver;
import java.io.*;
import java.net.*;
import java.security.*;
import javax.crypto.*;
public class GameServer {
public static void main(String arg[]) {
try {
ServerSocket ss = new ServerSocket(12346);
while(true) {
Socket s = ss.accept();
ClientHandler ch = new ClientHandler(s);
ch.start();
}
}
catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
class ClientHandler extends Thread {
Socket socket;
KeyPair keyPair = null;
public ClientHandler(Socket socket) {
this.socket = socket;
}
public KeyPair genKeyPair() {
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
keyPair = keyGen.generateKeyPair();
//PrivateKey privateKey = keyPair.getPrivate();
//PublicKey publicKey = keyPair.getPublic();
} catch (NoSuchAlgorithmException e) {
System.out.println(e.getMessage());
}
return keyPair;
}
public void run() {
try {
ObjectInputStream Ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream Oos = new ObjectOutputStream(socket.getOutputStream());
keyPair = genKeyPair();
PublicKey publicKey = keyPair.getPublic();
Oos.writeObject(publicKey);
socket.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}
問題是,當我按下按鈕時,客戶端似乎沒有連接到服務器,並且什麼也收不到,有什麼想法?感謝
你可能想嘗試更激烈的調試除了按按鈕,希望我們趟直通所有代碼。 – Filburt 2012-04-26 06:53:39
我改變了使用datainputsteam發送一個int到客戶端,它的工作原理,但objectinputsteam不工作...... – hkguile 2012-04-26 07:04:16
由於ObjectInputStream阻塞,請看我的帖子 – mprabhat 2012-04-26 07:08:18