[英]client server chat application gui
我正在使用tcp編寫一個簡單的客戶端服務器聊天應用程序。 但是消息不會轉發到客戶端/服務器,而是像無限循環那樣在終端中出現真正的隱秘錯誤,直到我終止進程或關閉應用程序。 任何人都可以建議對代碼進行更改。
class UIserver extends JFrame implements ActionListener {
JTextArea textArea;
JButton sendButton;
JTextField textField;
JScrollPane scrollpane ;
DataOutputStream dos = null;
DataInputStream dis = null;
Scanner scanner = new Scanner(System.in);
public UIserver(){
this.setTitle("Server");
this.setLayout(new FlowLayout());
textArea = new JTextArea(30,50);
textArea.setBackground(Color.white);
textArea.setLayout(new FlowLayout());
scrollpane = new JScrollPane(textArea);
getContentPane().add(scrollpane, BorderLayout.CENTER);
this.add(scrollpane);
sendButton = new JButton("Send");
this.add(sendButton);
sendButton.addActionListener(this);
textField = new JTextField(30);
this.add(textField);
this.setVisible(true);
this.setSize(600,600);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}//end ctor
public void setDataOutput(DataOutputStream dos){
this.dos = dos;
}
public void setDataInput(DataInputStream dis){
this.dis = dis;
}
public void getMsg(){
new Thread(new Runnable(){
public void run (){
while(true){
try {
String msg = dis.readUTF();
textArea.append("From Client :- "+msg+"\n");
}catch(Exception e){e.printStackTrace();}
}//end while
}
}).start();
}//end getmsg
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sendButton) {
new Thread(new Runnable(){
public void run (){
while(true){
try{
String msgsend = scanner.nextLine();
textArea.append("To Client :- "+msgsend+"\n");
//dos.writeUTF(msgsend);
}catch(Exception e){e.printStackTrace();}
}//end while
}
}).start();
}//end if
}//end actionPerformed
客戶端和服務器的這一部分相同
現在主要
服務器主要方法
public static void main(String[] args) throws Exception {
UIserver usi = new UIserver();
ServerSocket socket = new ServerSocket(5000);
Socket server = socket.accept();
DataInputStream dis = new DataInputStream(server.getInputStream());
DataOutputStream dos = new DataOutputStream(server.getOutputStream());
usi.setDataInput(dis);
usi.setDataOutput(dos);
usi.getMsg();
}//end main
客戶主要方法
public static void main(String[] args) throws Exception {
UIclient cli = new UIclient();
Socket socket = new Socket("localhost",5000);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
cli.setDataInput(dis);
cli.setDataOutput(dos);
cli.getMsg();
}//end main
就無限錯誤循環而言,我認為這是因為您在應用程序啟動時正在調用方法getMsg()
cli.getMsg();
永遠運行這個while循環
while(true){
try {
String msg = dis.readUTF();
textArea.append("From Client :- "+msg+"\n");
}catch(Exception e){e.printStackTrace();}
}
while總是正確的,並且異常會被捕獲並且堆棧跟蹤會不斷出現垃圾郵件,這可能是因為它試圖獲取尚不存在的消息,因為它會在啟動之前在任何消息存在之前運行? 也許我不確定。
嘗試刪除try塊的catch部分,看看是否可以發送消息而不會被堆棧跟蹤發送垃圾郵件。 像這樣...
while(true){
try {
String msg = dis.readUTF();
textArea.append("From Client :- "+msg+"\n");
}
finally{}
}
這不是最佳實踐,但是它可以使您滿懷希望地前進。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.