javaを使用して、フォーム、クライアントフォーム、サーバーフォーム、クライアントフォームにTextFieldとボタン(送信ボタン)、サーバーフォームにTextAreaを含む簡単なチャットプログラムを作成しようとしています。
送信ボタンをクリックすると、TextFieldに書き込まれたテキストがサーバーフォームのTextAreaに送信されます。
初めては機能しますが、2回目にボタンをクリックすると機能しません。
これは私がサーバーフォームで使用したコードです:
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();
}
}
});
}
}