我想創建一個簡單的聊天程序使用java,它包含窗體,客戶端窗體和服務器窗體,客戶端窗體包含一個TextField和一個按鈕(發送按鈕),並且服務器窗體包含一個TextArea。一個簡單的客戶端/服務器聊天程序
當我單擊發送按鈕時,它應該將TextField中的寫入文本發送到服務器表單中的TextArea。
它第一次工作,但當我第二次點擊按鈕時,它將無法正常工作。
這是我的服務器形式使用的代碼:
public class Server extends javax.swing.JFrame implements Runnable {
private Thread th;
public Server() {
initComponents();
th = new Thread(this);
th.start();
}
// The main method was here
@Override
public void run() {
// Etablir la connexion
try {
ServerSocket ecoute;
ecoute = new ServerSocket(1111);
Socket service = null;
System.out.println("Serveur en attente d'un client !");
while (true) {
service = ecoute.accept();
System.out.println("Client connécté !");
DataInputStream is = new DataInputStream(service.getInputStream());
jTextArea1.setText("Client dit : "+ is.readUTF().toUpperCase());
service.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
,這是客戶端形式的代碼:
public class Client extends javax.swing.JFrame {
DataOutputStream os;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
os.writeUTF(jTextField1.getText());
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE,null, ex);
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Client c = new Client();
c.setVisible(true);
try {
Socket s = new Socket("localhost", 1111);
c.os = new DataOutputStream(s.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
「*它第一次工作,但當我第二次點擊按鈕時,它將無法工作。*」。那麼會發生什麼呢?請明確點。 – Lion 2013-03-03 17:54:57
@Lion什麼都沒有發生,它什麼都做,它看起來像操作事件只有一次 – 2013-03-03 18:01:00
沒有例外記錄?這似乎很奇怪.. – ddmps 2013-03-03 18:04:12