为了账号安全,请及时绑定邮箱和手机立即绑定

java小白,聊天程序现在还只写了一个client端和一个server端

java小白,聊天程序现在还只写了一个client端和一个server端

紫衣仙女 2022-04-22 15:11:18
用client发消息 总是等client关闭 server才能收到消息 这是为什么啊 跪谢!! 代码如下:client:import java.awt.*;import java.awt.event.*;import java.io.*;import java.net.Socket;import java.net.UnknownHostException;public class ChatClient extends Frame{TextField tfTxt = new TextField();TextArea taContent = new TextArea();static Socket s;BufferedWriter bw = null;public static void main(String[] args) {ChatClient cc= new ChatClient();cc.connect();cc.launchFrame();}public void connect(){try {s = new Socket("127.0.0.1",9408);System.out.println("Connected!");bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));} catch (UnknownHostException e){e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public void launchFrame(){this.setLocation(400, 300);this.setSize(300,300);add(tfTxt,BorderLayout.SOUTH);add(taContent,BorderLayout.NORTH);pack();this.setVisible(true);tfTxt.addKeyListener(new KeyAdapter(){public void keyPressed(KeyEvent e){int a;a = e.getKeyCode();if(a == KeyEvent.VK_ENTER){String string =tfTxt.getText().trim();taContent.setText(string);tfTxt.setText("");try{System.out.println(string);bw.write(string);bw.flush();}catch(IOException ex){System.out.println(ex);}}}});this.addWindowListener(new MyMonitor());}public void disConnect(){try {bw.close();s.close();} catch (IOException e) {e.printStackTrace();}}}class MyMonitor extends WindowAdapter{public void windowClosing(WindowEvent e){ChatClient f =(ChatClient) e.getSource();f.disConnect();System.exit(0);}}server端:import java.io.*;import java.net.*;public class ChatServer {static Socket s = null;static ServerSocket ss = null;public static void main(String[] args) {try {ss = new ServerSocket(9408);while(true){s = ss.accept();System.out.println("a client has connect");BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));String string = br.readLine();System.out.println(string);br.close();}} catch (IOException e) {e.printStackTrace();}}}
查看完整描述

2 回答

?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

问题在 你这个
public void windowClosing(WindowEvent e){
ChatClient f =(ChatClient) e.getSource();
f.disConnect();
System.exit(0);
}
方法里,当你关闭窗口的时候 流才关闭 你这个关闭流的方法 没必要写在这里 你自己琢磨琢磨怎么改。

查看完整回答
反对 回复 2022-04-24
?
翻翻过去那场雪

TA贡献2065条经验 获得超13个赞

太长了,建议你检查一下你代码的顺序有没有问题,如果服务器端用循环一直处于阻塞待接收数据的状态,侃侃是不是输出流放在循环外面了?

查看完整回答
反对 回复 2022-04-24
  • 2 回答
  • 0 关注
  • 135 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信