java applet - simple version of multi-person chat room

Posted by karldenton on Mon, 02 Sep 2019 14:59:07 +0200

Functional requirements:

1. Each time the main function is run, a client chat interface is created.

2. The client interface is divided into three parts: the public screen (displaying all the information sent by the client), the private screen (for inputting the information that the individual wants to send), and the sending button (clicking once to send the client information to the server).

3. Welcome xxx to the multi-person chat room when entering the client. When closing the client, remind XXXX to leave the chat room

4. The client is displayed at the end of the article, and the address of the source file is also at the end of the article. It can be directly turned to the end.

============================================================================

Knowledge required:

1 IO Stream Basic Knowledge for Reading, Writing and Sending Information

2 Jframe jpane for creating graphical interfaces

3. Socket Basic Knowledge, Used to Create Client, Server and Transfer Information to Each Other

4 Thread Basic Knowledge

5. Basic knowledge of timers

======================================================================

Main ideas:

1. Create client interface.

2. Create a client in the interface and send information to the server every click.

3. The server always opens and receives client information continuously. Then it sends the received information to all clients.

4. The client displays the information sent by the server on the public screen

===========================================================================

The code is as follows:

Step 1: Draw the client's outer border

/**
 * @Title: chatJFrame.java
 * @Package view
 * @Description: 
 * @author Mr.Yao
 * @date 2019 August 28, 2000, 4:53:47 p.m.
 * @version V1.0
*/
package chatview;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.Scanner;

import javax.swing.JFrame;

/**
 * @ClassName: chatJFrame
 * @Description: Inherit JFrame, Draw Chat Interface Outer Border
 * @author Mr.Yao
 * @date 2019 August 28, 2000, 4:53:47 p.m.
 *
*/
public class ChatJFrame extends JFrame {
    //Rewrite Construction Method
    public ChatJFrame() {
        //Output lets the user enter a username,As the name of the subsequent client
        System.out.println("enter one user name");
        Scanner input=new Scanner(System.in);
        String name=input.next();
        //Set up the name of the chat room
        this.setTitle(name);
        //Get the screen
        Toolkit dt = Toolkit.getDefaultToolkit();
        Dimension ss = dt.getScreenSize();
        //Get screen width and height
        int width = (int)ss.getWidth();
        int height = (int)ss.getHeight();
        //Set center and width
        this.setBounds((width - 500) /2,(height - 500)/2,500,500);
        //Add to chatJPanl object,Add canvas,And pass in the name
        this.add(new ChatJPanel(name));
        //Setting Disable Window Zooming
        this.setResizable(false);
        //Close when closing window JVm,
        this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
        //Settings visible
        this.setVisible(true);
        
    }
    
}

=====================================================================

The second step is to create the canvas and establish the client

How to send information by clicking Send button?--------------> Click on the event of building button, click once to get the information of the current text input box, and write it to the server using write() method

How to continuously receive information from the server?------------------> Execute it every 0.5s with a timer, and display it to the public screen if the server sends information.

 

/**
 * @Title: chatJPane.java
 * @Package view
 * @Description: 
 * @author Mr.Yao
 * @date 2019 August 28, 2000, 4:54:05 p.m.
 * @version V1.0
*/
package chatview;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;

/**
 * @ClassName: chatJPane
 * @Description: Inheritance of JPanl class, used to draw three areas in the graphics, and establish the function of sending and receiving information by the client
 * @author Mr.Yao
 * @date 2019 August 28, 2000, 4:54:05 p.m.
 *
*/
public class ChatJPanel extends JPanel{
    //Declaration name string,Used for receiving chatJFrame Passed in user name
    public String name;
    
    //Add text fields,As a chat information public screen box
    public JTextArea screen; 
    //Add text fields,As user information input box
    public JTextArea input; 
    //Add send button,Click on the button,Send out input box information
    public JButton send; 
    
    //Affirmation Client
    public Socket socket;
    //Declare client output,Input stream
    OutputStream os;
    InputStream is;
    
    //Parametric-free construction method
    public ChatJPanel() {}
    
    //Parametric structure
    public ChatJPanel(String name) {
        //Receiving User Name
        this.name=name;
        //Cancel Flow Layout
        this.setLayout(null);
        
        //Create the public screen and set the width and height
        screen=new JTextArea();
        screen.setBounds(20, 20, 450, 280);
        this.add(screen);
        
        //Create input box and set width and height
        input=new JTextArea();
        input.setBounds(20,320,300,120);
        this.add(input);
        
        //Create buttons,And set width and height
        //Button object
        send = new JButton();
        send.setBounds(340, 320, 100, 120);
        send.setText("SEND");
        this.add(send);
        
        //New Client Object,And settings ip Address and port number
        try {
            socket=new Socket("127.0.0.01",12321);
            //Get client input and output streams
            os=socket.getOutputStream();
            is=socket.getInputStream();
            //Output welcome xxx Come to the chat room
            String s="Welcome"+name+"Come to the chat room!!!!";
            os.write(s.getBytes());
            os.flush();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        /*Add a click function to the button and send the input box information to the server when clicking the button.*/
        send.addActionListener(new ActionListener() {

            @Override
            //override method
            public void actionPerformed(ActionEvent e) {
                //Get the current content of the input box,And add the user name            
                String text = name+"say:"+input.getText();
                //Output the input box to the server
                try {
                    //write
                    os.write(text.getBytes());
                    //Refresh
                    os.flush();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                //Clear the input box
                input.setText("");
            }            
        });
        //Create a timer,Start every 500 milliseconds,Receiving messages from the server
        new Timer().schedule(new TimerTask() {
            
            @Override
            //override method,Receiving information from the server
            public void run() {
                // TODO Auto-generated method stub
                //Define strings,Accept the information returned by the server
                String text="";
                try {
                    //Establish byte array,Save the byte information returned by the server
                    byte[] b=new byte[1024];
                    //Define the number of bytes read by variable records
                    int len=-1;
                    //Read the server to return bytes
                    len=is.read(b);
                    //Converting to Characters
                    text=new String(b,0,len);
                        
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if(text!="") {
                    //Add to screen
                    screen.append(text+"\n");    
                }
            }
        },500,500);    
    }
}

 ===========================================================================

Step 3: Create a server

How to make the service continuously accept different client information and send it to all clients?-------> The service is always open, using the dead loop while() to continuously accept client soket s, adding each one to a collection and creating a thread. The content of the thread is to traverse the collection and send the information received by the server to the institute. Have client

Create a collection to save socket s accepted by the server

/**
 * @Title: ServerList.java
 * @Package chatserver
 * @Description: 
 * @author Mr.Yao
 * @date 2019 August 28, 2000, 7:56:41 p.m.
 * @version V1.0
*/
package chatserver;

import java.net.Socket;
import java.util.ArrayList;

/**
 * @ClassName: ServerList
 * @Description: Create a collection and save each client's socket
 * @author Mr.Yao
 * @date 2019 August 28, 2000, 7:56:41 p.m.
 *
*/
public class ServerList {
    //Create collections
    public static ArrayList<Socket> list=new ArrayList<Socket>();
}

 

The server class is used to accept clients and open threads. It also needs to create a thread class and rewrite the run method. The rewritten run method is used to traverse the collection and output information to all clients.

/**
 * @Title: Server.java
 * @Package chatserver
 * @Description: 
 * @author Mr.Yao
 * @date 2019 August 28, 2000, 7:53:37 p.m.
 * @version V1.0
*/
package chatserver;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ClassName: Server
 * @Description: Create a server to continuously receive client information
 * @author Mr.Yao
 * @date 2019 August 28, 2000, 7:53:37 p.m.
 *
*/
public class Server {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //Create a server
        ServerSocket ss = null;
        try {
            ss=new  ServerSocket(12321);
            //Receiving Client Loop
            while(true) {
                Socket socket = ss.accept();
                //take socket Add to the array
                ServerList.list.add(socket);
                //Create an anonymous thread and start it
                new Thread(new ServerThread(socket)).start();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
}

ServerThread class implements runnable interface and rewrites run method

/**
 * @Title: ServerThread.java
 * @Package chatserver
 * @Description: 
 * @author Mr.Yao
 * @date 2019 August 29, 2000, 11:58:47 a.m.
 * @version V1.0
*/
package chatserver;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @ClassName: ServerThread
 * @Description: Create thread classes to recycle information from clients and send it to all clients
 * @author Mr.Yao
 * @date 2019 August 29, 2000, 11:58:47 a.m.
 *
*/
public class ServerThread implements Runnable {
    //Declare variables,Accept User Client Name,For output XXX Offline
    public String  name=null;
    //statement socket object
    public Socket socket;
    //Parametric structure
    public ServerThread() {}
    //Parametric structure
    public ServerThread(Socket socket) {
        this.socket=socket;
    }
    
    //Rewrite run Method
    @Override
    public void run() {
        // TODO Auto-generated method stub
        //Create an input stream
        try {
            InputStream is=socket.getInputStream();
            //Continuous acceptance of client information
            while(true) {
                //Accept client information
                byte[] b=new byte[1024];
                int len=-1;
                len=is.read(b);
                //Get the customer name,Welcome from the first sentence xxx Go to the client and intercept the name
                String string=new String(b,0,len);
                if(string.contains("Welcome")&&name==null) {
                    //Intercept name
                    name=string.substring(2,string.indexOf("come"));
                }
                //Send this information to each client
                for(Socket socket:ServerList.list) {
                    //Create an output stream
                    OutputStream os=socket.getOutputStream();
                    //Output information
                    os.write(b, 0, len);
                    //Refresh
                    os.flush();
                }
            }
        }catch (IOException e) {
            // TODO: handle exception
            //Abnormality,Explain that the client is closed,Send information to other online clients:xxx Offline
            //    e.printStackTrace();
            //Closed in the collection socket Object deletion,
            ServerList.list.remove(this.socket);
            //Cyclic Output Information
            for(Socket socket:ServerList.list) {
                //Create an output stream
                try {
                    OutputStream os = socket.getOutputStream();
                    //Output information
                    os.write((name+"Offline").getBytes());
                    //Refresh
                    os.flush();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    }
}

                
                
                            

 

Step 4: Create the startup class and write the main function

 

/**
 * @Title: ChatStart.java
 * @Package chatstart
 * @Description: 
 * @author Mr.Yao
 * @date 2019 August 28, 2000, 7:51:14 p.m.
 * @version V1.0
*/
package chatstart;

import chatview.ChatJFrame;

/**
 * @ClassName: ChatStart
 * @Description: Main Method, Program Entry
 * @author Mr.Yao
 * @date 2019 August 28, 2000, 7:51:14 p.m.
 *
*/
public class ChatStart {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //Establish jf Border object
        ChatJFrame jf=new ChatJFrame();
    }

}

 

==============================================================================================

Operation effect demonstration:

--> You need to run the server first and start the server. Then you need to run the main function. Every time you run it, you create a client.

 

Source file directory structure:

 

  

 

Source code:

Link: https://pan.baidu.com/s/18aPqsoJsP4ZYf6ZkWzU-g
Extraction code: exva

Topics: Java socket jvm