public class ChatServer { boolean started = false; ServerSocket serverSocket = null; public void start(){ //DataInputStream inputStream = null; try { serverSocket = new ServerSocket(8888); }catch(BindException e){ System.out.println("端口被占用"); System.exit(0); }catch(IOException e){ e.printStackTrace(); } try { started = true; while(started){ Socket socket = serverSocket.accept(); Client c = new Client(socket); new Thread(c).start(); } }catch (IOException e) { }finally{ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } class Client implements Runnable{ private DataInputStream inputStream = null; private Socket socket = null; private boolean connect = false; public Client(Socket socket) { this.socket = socket; connect = true; try { inputStream = new DataInputStream(socket.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } public void run() { try { while(connect){ String str = inputStream.readUTF(); System.out.println("客户端发送--->"+str); } }catch (EOFException e){ //客户端关闭 }catch (IOException e) { }finally{ try { if(inputStream!=null)inputStream.close(); //客户端掉线,或关闭了 if(socket!=null)socket.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } public static void main(String[] args) { ChatServer chatServer = new ChatServer(); chatServer.start(); }}
public class ChatClient extends Frame{ private static final long serialVersionUID = 287499141806289407L; TextField textField = new TextField(); TextArea textArea = new TextArea(); Socket socket = null; DataOutputStream outputStream = null; public void launchFrame(){ setSize(300, 300); setLocationRelativeTo(null); add(textArea, BorderLayout.NORTH); add(textField,BorderLayout.SOUTH); pack(); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { disconnect(); System.exit(0); } }); textField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //TextField field = (TextField)e.getSource(); String text = textField.getText(); textArea.setText(text); textField.setText(""); try { outputStream.writeUTF(text); outputStream.flush(); //outputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } //System.out.println("文本框输入"+field.getText()); } }); setVisible(true); connect(); } public void connect(){ try { socket = new Socket("localhost", 8888); outputStream = new DataOutputStream(socket.getOutputStream()); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void disconnect(){ try { outputStream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { ChatClient client = new ChatClient(); client.launchFrame(); }}