How to use keyevent in client server communication

239 Views Asked by At

I'm new to java and I have to create a client server communication that transmits the message as its being typed. I've tried using various key events but It only seems to transmit with the keyrelease event. Thread.sleep(3000) is used because I am required to delay the message by 3 seconds.

When I type a word into jTextArea2 only the first letter appears in jTextArea2 in the client page

Server code

 static ServerSocket ss;
 static Socket s;
 static DataInputStream din;
  static DataOutputStream dout;
 KeyListener key = new KeyListener(){
     public void keyPressed(KeyEvent keyEvent){



     }
     public void keyReleased(KeyEvent keyEvent){
           String msgout ="";
         try{  
     Thread.sleep(3000);
    msgout = jTextArea2.getText().trim();
    dout.writeUTF(msgout);
  }catch(Exception e){
     System.err.println("Exception:" + e.getMessage());  
  }
     }

     public void keyTyped(KeyEvent keyEvent){

     }
 };


     String msgin = "";
    try{
     ss = new ServerSocket(1201);
     s = ss.accept();
     din = new DataInputStream(s.getInputStream()); 
     dout = new DataOutputStream(s.getOutputStream());

     while (!msgin.equals("exit")){
      msgin = din.readUTF();

      jTextArea1.setText(jTextArea1.getText().trim() + msgin);
     }
    }catch(Exception e){
      System.err.println("Exception:" + e.getMessage());   
    }

 }  

}

Also when I type something into jTextArea2 nothing appears in jTextArea2 in the server page

Client code

  static Socket s;
 static DataInputStream din;
  static DataOutputStream dout;
  KeyListener key = new KeyListener(){
     public void keyPressed(KeyEvent keyEvent){

     }
     public void keyReleased(KeyEvent keyEvent){
              String msgout ="";
         try{  
     Thread.sleep(3000);
    msgout = jTextArea2.getText().trim();
    dout.writeUTF(msgout);
  }catch(Exception e){
     System.err.println("Exception:" + e.getMessage());  
  }  
     }
     public void keyTyped(KeyEvent keyEvent){

     }
 };
 public static void main(String[] args) {
 java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Chatclient().setVisible(true);
        }
    });
 String msgin = "";
 try{

      s = new Socket("127.0.0.1",1201);
      din = new DataInputStream(s.getInputStream());
      dout = new DataOutputStream(s.getOutputStream());


      msgin = din.readUTF();
      jTextArea1.setText(jTextArea1.getText().trim()+ msgin);

 }
 catch (Exception e){
   System.err.println("Exception:" + e.getMessage());  
 }

    }

}

0

There are 0 best solutions below