用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();}}}
添加回答
举报
0/150
提交
取消