同上 谢谢

解决方案 »

  1.   

    //这是客户端 自己把socket的IP改了就能用
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;import javax.swing.*;public class MyChat{
    JFrame frame;
    Container con;
    JPanel panel;
    JTextArea textArea;
    JLabel label;
    JTextField textField;
    JScrollPane scrollPane;
    JButton addButton;
    JButton clearButton;
    Socket s;
    BufferedReader in;
    PrintWriter out;
    String textRe;
    boolean isStart ;
    static String clientName ;
    public static void main(String[] args)throws Exception {
    clientName = args[0];
    new MyChat().init();
    } public void init()throws Exception{
    frame = new JFrame("MyChat");
    con = frame.getContentPane();
    panel = new JPanel();
    textArea = new JTextArea();
    textArea.setEditable(false);
    scrollPane = new JScrollPane(textArea);
    label = new JLabel("please input:");
    textField = new JTextField();
    addButton = new JButton("OK");
    clearButton = new JButton("Clear");
    textRe="";
    isStart=true;
    s=new Socket("127.0.0.1",8000);
    in=new BufferedReader(new InputStreamReader(s.getInputStream()));
    out=new PrintWriter(s.getOutputStream());
    go(); }
    public void go(){
    con.setLayout(new BorderLayout(2,1));
    panel.setLayout(new GridLayout(2,2));
    con.add(scrollPane,BorderLayout.CENTER);
    con.add(panel,BorderLayout.SOUTH);
    panel.add(label);
    panel.add(textField);
    panel.add(addButton);
    addButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent arg0) {
    String text=textField.getText();
    textField.setText("");
    out.println(clientName+": "+text);
    out.flush();
    }});
    clearButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent arg0) {
    textArea.setText("");
    textField.setText("");
    }});
    textField.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent arg0) {
    String text=textField.getText();
    textField.setText("");
    out.println(clientName+": "+text);
    out.flush();
    }});
    frame.addWindowListener(new WindowAdapter(){
    public void windowActivated(WindowEvent arg0) {
    textField.requestFocusInWindow();
    }});
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
    try { 
    isStart=false;
    out.println(clientName +" is leaving");
    out.flush();
    out.println("78987");
    out.flush();
    s.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    System.exit(0);
    }
            });
    panel.add(clearButton);
    frame.setSize(200,300);
    frame.setVisible(true);
    out.println(clientName+": is coming!");
    out.flush();
    while(isStart){
    try {
    textRe = in.readLine();
    } catch (Exception e) {
    e.printStackTrace();
    break;
    }
    textArea.append(textRe+"\n");
    }
    }



    }