gpt4 book ai didi

java - 构建一个简单的聊天客户端

转载 作者:行者123 更新时间:2023-11-30 11:52:52 25 4
gpt4 key购买 nike

我正在构建一个简单的聊天客户端,它只能发送和接收消息。

我使用在我自己的计算机上运行的服务器,该服务器将发送给它的任何消息发回给连接到该服务器的所有用户。

当我通过单击“发送按钮”向服务器发送消息时,服务器没有按预期将消息发回给我。因此,要么我的输出流不工作,要么我的输入消息监听器不工作但无法找出问题所在。

我可能会补充一点,我没有收到任何错误消息/异常并且连接到服务器工作正常

public class Chatt extends JFrame implements Runnable{
private JPanel topPanel = new JPanel();
private JPanel bottomPanel = new JPanel();
private JTextArea chattArea = new JTextArea();
private JButton sendButton = new JButton("Skicka");
private JLabel chattPerson = new JLabel("Du chattar med: ");
private JTextField chattField = new JTextField(15);
private Thread thread;
private int port;
private String ip;
private DataInputStream in;
private DataOutputStream out;
private Socket s;


public Chatt(String ip, int port){
this.ip=ip;
this.port=port;
Konstruktor();
}
public Chatt(){
ip="127.0.0.1";
port=2000;
Konstruktor();
}
public Chatt(String ip){
this.ip=ip;
port=2000;
Konstruktor();
}

public void Konstruktor(){
setLayout(new BorderLayout());

chattArea.setSize(70, 50);
add(chattArea, BorderLayout.CENTER);

bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
bottomPanel.add(sendButton);
bottomPanel.add(chattField);
sendButton.addActionListener(new sendListener());
add(bottomPanel, BorderLayout.SOUTH);

topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
topPanel.add(chattPerson);
add(topPanel, BorderLayout.NORTH);

try {
//s = new Socket("atlas.dsv.su.se", 9494);
s=new Socket(ip, port);
}
catch (UnknownHostException e) {
System.out.println("Connection failed");
}
catch (IOException e) {
}
try{
in= new DataInputStream(new BufferedInputStream(s.getInputStream()));
out= new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));
}
catch(UnknownHostException e){
System.out.println("Host unknown");
}
catch(IOException e){

}
thread = new Thread(this);
thread.start();

setTitle("Connected to "+ip+" på port "+port);
chattArea.setEditable(false);
setSize(400, 500);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void run() {

while(true){
System.out.println("tråden igång");
try {
String temp = in.readUTF();
System.out.println(temp);
chattArea.append(temp);
} catch (IOException e) {

}

}
}


public class sendListener implements ActionListener{
public void actionPerformed(ActionEvent e){
String chattString = chattField.getText();
try {
out.writeUTF(chattString);
out.flush();
}
catch (IOException e1) {

}
chattArea.append("Du: "+chattString+"\n");
chattField.setText("");

}

}



public static void main(String[] args){
//new Chatt("127.0.0.1", 2000);
//new Chatt();
new Chatt("127.0.0.1");
}

}

最佳答案

我可以确认聊天服务器没有正常工作。我确实构建了自己的服务器并且发送/接收消息工作正常,所以我的代码没有问题。

关于java - 构建一个简单的聊天客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6615459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com