Socket and write between JAVAswing chat room

In the first phase of Xiamen to our review of the JAVASE basis, the first phase of small toys that we optional subjects, I chose this chat room content, whether it is this little toy thread, or network programming, will be involved, we have more comprehensive, so I chose this;

This is my bag structure:

Class package, JDBC kits, interface package

First, talk about ideas, chat rooms are a platform for data transmission end to end, however Socket generally only a point to point data transmission, so, in order to solve this problem, I will be all clients access this server-side gave receiving a List, he is determined by the statement will be removed leaving, put the broadcast information to the client when the List messaging client, code is as follows:

public class Server {
    int port;
    List<Socket> clients;//接入本服务器的客户端
    ServerSocket server;

    public static void main(String[] args) {
        new Server();
    }

    public Server() {
        try {
            port = 8080;
            clients = new ArrayList<Socket>();
            server = new ServerSocket(port);
            System.out.println("...........");
            while( To true ) {
                 // always monitor whether or not the client has access, access is added 
                the Socket Socket = server.accept (); 
                System.out.println (Socket); 
                clients.add (Socket); 
                myThread MyThread = new new myThread ( Socket); 
                mythread.start (); 
                
            } 

        } the catch (Exception EX) { 
            ex.printStackTrace (); 
        } 
    } 
    class myThread the extends the Thread { 
        the Socket ssocket; 
        Private the BufferedReader br;
         PrivatePW the PrintWriter;
         public String MSG; 

        public myThread (the Socket S) { 
            ssocket = S; 
        } 

        public  void RUN () {
             // if the method is for monitoring of messages sent by the client 
            the try { 
                br = new new the BufferedReader ( new new the InputStreamReader ( 
                        ssocket .getInputStream ())); 
                msg = "Welcome to the chat room chat rooms currently have! [" 
                        + clients.size () + "] people" ; 
                SendMsg (); 
                the while ((msg = br.readLine ()) =! null ) {
                    MSG = "{" + ssocket.getInetAddress () + "]" + MSG; 
                    SENDMSG (); 

                } 
            } the catch (Exception EX) { 
                ex.printStackTrace (); 
            } 
        } 

        public  void SENDMSG () {
             the try { // monitoring hair whether the content is a leaving format 
                System.out.println (MSG); 
                String [] aaStrings = msg.split ( "-" );
                 for ( int I = 0; I <clients.size (); I ++ ) {
                     iF(clients.get (I) .toString (). Split ( ",") [0 ] 
                            .equals (aaStrings [ . 1] .split ( ",") [0 ])) { 
                        System.out.println ( "was left a chat room !! " ); 
                        clients.remove (I); 
                        BREAK ; 
                    } 
                } 

            } the catch (Exception EX) {
                 for ( int I = 0; I <clients.size (); I ++) { // iterate send 
                    try { 
                        PW = new new the PrintWriter (clients.get (I) .getOutputStream (),
                                 to true);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    pw.println(msg);
                    pw.flush();
                }
            }

        }
    }

}

This issue is resolved, the client will not be a problem, and I send messages encapsulated in the Client:

public class ClientDao {
        Socket socket;
        String message;
        
        public ClientDao(String message, Socket socket) {
            this.message = message;
            this.socket = socket;
        }
        //发送消息
        public void send(String message, Socket socket) {
            OutputStream os;
            try {
                //获取socket的输出流
                os = socket.getOutputStream();
                BufferedWriter bw = new BufferedWriter(newThe OutputStreamWriter (OS));
                 // message sent 
                bw.write (Message);
                 // wrap 
                bw.newLine (); 
                bw.flush (); // empty the cache 
            } the catch (IOException E) {
                 // the TODO Auto- Block the catch Generated 
                e.printStackTrace (); 
            } 
        } 
    
}

 

Since I need to transmit information to the user the next page, so I will be rewritten constructor window specific codes are as follows :

 

public class TalkClient extends JFrame {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JTextField sendText;
    private JTextArea jta;
    public static boolean connect = false; // 客户端是否连接
    ClientDao cDao;
     public int port = 8080;
        Socket socket = null;
        String msg2;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TalkClient frame = new TalkClient();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public TalkClient() {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                msg2= "asdasd" +"-"+socket+"-"+"close";
                cDao=new ClientDao(msg2, socket);
                cDao.send(msg2, socket);
                
                
            }
        });
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 505, 477);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        sendText = new JTextField();
        sendText.setBounds(120, 257, 343, 43);
        contentPane.add(sendText);
        sendText.setColumns(10);
        
        
        
        JLabel label = new JLabel("\u6D88\u606F\u8BB0\u5F55\uFF1A");
        label.setBounds(34, 15, 76, 15);
        contentPane.add(label);
        jta= new JTextArea();
        JScrollPane jsp = new JScrollPane(jta);
        jsp.setBounds(120, 10, 343, 220);
        jsp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        getContentPane().add(jsp);
        JLabel label_1 = new JLabel("\u5F85\u53D1\u9001\u6D88\u606F\uFF1A");
        label_1.setBounds(34, 271, 76, 15);
        contentPane.add(label_1);
        JLabel namelb = new JLabel("");
        namelb.setBounds(90, 354, 54, 15);
        contentPane.add(namelb);  
        JButton sendBtn = newThe JButton ( "\ u53D1 \ u9001" ); 
        sendBtn.addActionListener ( new new the ActionListener () {
             public  void the actionPerformed (the ActionEvent E) {
                 // send message
                 // Msg2 = sendText.getText () toString () TRIM ();..
                 / / jta.append ( "\ n-client said:." + sendText.getText () toString ()); 
                Msg2 = sendText.getText () toString ();.
                 // System.out.println (Socket); 
                CDao = new new ClientDao (Msg2, Socket); 
                cDao.send (Msg2, Socket); 
                
            } 
        });
        sendBtn.setBounds(301, 350, 93, 23);
        contentPane.add(sendBtn);
        connectServer();
        
        
        new Thread(new Runnable() {
            public void run() {
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String msg1;
                    while ((msg1 = br.readLine()) != null) {
                        jta.append("\n"+":"+msg1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    
    
    
    
    
    public TalkClient(final User user) {
        // TODO Auto-generated constructor stub
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 505, 477);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        sendText = new JTextField();
        sendText.setBounds(120, 257, 343, 43);
        contentPane.add(sendText);
        sendText.setColumns(10);
        
        
        
        JLabel label = new JLabel("\u6D88\u606F\u8BB0\u5F55\uFF1A");
        label.setBounds(34, 15, 76, 15);
        contentPane.add(label);
        
        jta= new JTextArea();
        JScrollPane jsp = new JScrollPane(jta);
        jsp.setBounds(120, 10, 343, 220);
        jsp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        getContentPane().add(jsp);
        
        JLabel label_1 = new JLabel("\u5F85\u53D1\u9001\u6D88\u606F\uFF1A");
        label_1.setBounds(34, 271, 76, 15);
        contentPane.add(label_1);
        
        JLabel namelb = new JLabel("");
        namelb.setBounds(90, 354, 54, 15);
        contentPane.add(namelb);  
        
        JButton sendBtn = new JButton("\u53D1\u9001");
        sendBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //發送消息
                //jta.append(user.getUserName() + sendText.getText().toString());
                msg2 =user.getUserName()+"说:"+ sendText.getText().toString() ;
                //System.out.println(socket);
                cDao=new ClientDao(msg2, socket);
                cDao.send(msg2, socket);
                
            }
        });
        sendBtn.setBounds(301, 350, 93, 23);
        contentPane.add(sendBtn);
        connectServer();
        namelb.setText(user.getUserName());
        
        new Thread(new Runnable() {
            public void run() {
                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String msg1;
                    while ((msg1 = br.readLine()) != null) {
                        System.out.println("xiaoxi"+msg1);
                        jta.append("\n"+msg1);
                    }
                } catch(Exception E) { 
                    e.printStackTrace (); 
                }
            }
        .}) Start (); 
        
    
            addWindowListener ( new new WindowAdapter An () { 
                @Override 
                public  void the windowClosing (WindowEvent E) { 
                    Msg2 = user.getUserName () + "-" + Socket + "- "+" Close " ; 
                    CDao = new new ClientDao (Msg2, Socket); 
                    cDao.send (Msg2, Socket); 
                } 
        }); 
        

       
    } 
    public  Boolean ConnectServer () {
         the try {
             // Get the IP address entered, and connected 
            Socket = new new the Socket ( "192.168.6.196", 8080);
            jta.append("\n连接服务器成功!");
            connect = true;
            return true;
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            jta.append("\n连接失败");
        }
        return false;
    }
}

 

I am not here to those JDBC, Tieshanglai, basically like this

Guess you like

Origin www.cnblogs.com/Xjx-zhenCai/p/11094866.html
Recommended