我的聊天服务器不会向客户端发送消息

时间:2014-05-12 08:51:44

标签: java multithreading

我有这个代码可以聊天

但它不起作用,但有人告诉我,我应该使用字节数组和字符串,但我不明白,我希望你可以帮我解决这个问题,这段代码属于服务器......

 public void run() {
    try {
        ServerSocket= new ServerSocket(44444);//inside there is the port mumber which will be gain later from firstscreen
        ClientSocket= ServerSocket.accept();
        OUT=  new ObjectOutputStream(ClientSocket.getOutputStream());
        IN=new ObjectInputStream(ClientSocket.getInputStream());
        while (true){
            Object input =IN.readObject();
        textArea.setText(textArea.getText()+"Client:"+(String)input+"\n");//update the textarea
        }//loop end

    }catch (IOException e){
        //joptionpane
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        //joptionpane
        e.printStackTrace();
    }   
}//end of try

public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals("Send")|| e.getSource() instanceof JTextField){
        try {
            if(textField.getText().isEmpty()) {
            OUT.writeObject(textField.getText());
            textArea.setText(textArea.getText()+"Assistant:"+textField.getText()+"\n");}    
        }
        catch (IOException c){
            c.printStackTrace();
        }
    }

1 个答案:

答案 0 :(得分:0)

我希望您明白,您只是让一个SINGLE客户端连接到服务器,因为不会发生任何其他serverSocket.accept()

首先,如果if(textField.getText().isEmpty())的文本域文本为​​空,那么您只是发送信息,这是非常无稽之谈,否则没有调用通过套接字发送任何数据。

除此之外,我没有看到actionPerformed块的代码,我假设你之前用JButton左右编码了它并实现了jbutton.addActionListener()

另外,我希望ClientSocket是你自己的一个类,因为客户端被表示为Socket,而不是ClientSocket。

另一方面,我建议使用以下API writeUTF并忘记在DataInput和DataOutputStreams的帮助下将字符串转换为字节或其他方式。

代码将保留为:

public void run() {
try {
    ServerSocket serverSocket= new ServerSocket(44444);//inside there is the port mumber which will be gain later from firstscreen
    Socket clientSocket= serverSocket.accept();
    DataOutputStream OUT =  new DataOutputStream(clientSocket.getOutputStream());
    DataInputStream IN = new DataInputStream(clientSocket.getInputStream());
    while (true){
        String input = IN.readUTF();
        textArea.append(input+"\n"); //update the textarea
    }//loop end

}catch (IOException e){
    //joptionpane
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    //joptionpane
    e.printStackTrace();
}   
}//end of try



public void actionPerformed(ActionEvent e) {
  if(e.getActionCommand().equals("Send")|| e.getSource() instanceof JTextField) {
    try {
        if(!textField.getText().isEmpty()) { //Do not forget to include the ! (NOT)
            OUT.writeUTF(textField.getText());
            textArea.setText(textArea.getText()+"Assistant:"+textField.getText()+"\n");
        }    
    }
    catch (IOException c){
        c.printStackTrace();
    }
 }

}

我希望能够帮助过你。