我是java的新手,我必须创建一个客户端服务器通信,在输入时传输消息。我尝试过使用各种关键事件,但它似乎只是通过keyrelease事件传输。使用Thread.sleep(3000)是因为我需要将消息延迟3秒。
当我在jTextArea2中输入一个单词时,只有第一个字母出现在客户页面的jTextArea2中
服务器代码
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());
}
}
}
当我在jTextArea2中输入内容时,服务器页面中的jTextArea2中没有任何内容出现
客户端代码
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());
}
}
}