Home WeChat Applet Mini Program Development Real-time group chat applet development record

Real-time group chat applet development record

Feb 10, 2017 pm 01:31 PM
Multithreading client Server Program development

Yesterday I recalled a real-time group chat applet I made before. Written in JAVA. The development steps are as follows:

This is process-oriented development.

The first step is to establish the server side.

The second step is to establish the client and connect to the server.

The third step is that the client sends a message and the server can receive it.

The fourth step is to realize multiple clients connecting to the server and receive messages from multiple clients. Multi-threading and asynchronous methods can be used to solve the situation where the server is occupied.

The fifth step is that the server forwards the information sent by the client to each client.

The sixth step is to eliminate small bugs.

ChatServer.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.util.*;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class ChatServer
{
    boolean started = false;
    ServerSocket ss = null;
                           
    List<Client> clients = new ArrayList<Client>();
                           
                           
    public static void main(String[] args)
    {
        new ChatServer().start();  
    }
    public void start(){
        try
        {
            ss = new ServerSocket(8881);
        }
        catch (BindException e){
            System.out.println("端口已被占用!");
            System.out.println("请结束相关进程!");
            System.exit(0);
        }
        catch (Exception e) {
                                   
            e.printStackTrace();
        }
        try{
            started = true;
            while (started)
            {
                Socket s = ss.accept(); //阻塞性函数,不断接收客户端连接
                Client c = new Client(s);//不能再静态main()里面new一个动态的方法,故将启动过程包装成一个public函数
System.out.println("a client connected");
                new Thread(c).start();
                clients.add(c);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }finally{
            try
            {
                ss.close();
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
                               
    }
                           
    class Client implements Runnable{//区分客户端,用一个线程操作一个客户端,也可以采用异步的方法。这里用线程,比较占资源。等我写出异步的方法后再共享。
        private Socket s= null;
        private DataInputStream dis= null;
        private DataOutputStream dos=null;
        private boolean bConnected = false;
        public Client(Socket s){
            this.s= s;
            try
            {
                dis=new DataInputStream(s.getInputStream());
                dos=new DataOutputStream(s.getOutputStream());
                bConnected = true;
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                                   
        }
                               
        public void send(String str){       //
            try
            {
                dos.writeUTF(str);
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                clients.remove(this);
                System.out.println("一个客户退出了!List已去除");
                //e.printStackTrace();
            }
        }
                               
        public void run()
        {
            try
            {
                while (bConnected)
                {
                    String str;
                    str = dis.readUTF();// 阻塞性函数,会一直占用线程资源
System.out.println(str);
                    for (int i = 0; i < clients.size(); i++)
                    {
                        Client c = clients.get(i);
                        c.send(str);
                    }
                }
            }
            catch (EOFException e){
                System.out.println("一个客户已退出!");
            }catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                if(dis!=null)
                    try
                    {
                        dis.close();
                        if (dos != null)
                            dos.close();
                        if (s != null)
                            s.close();
                    } catch (SocketException e)
                    {
                            clients.remove(this);
                            System.out.println("一个客户已退出!");
                    }
                    catch (IOException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                                       
            }
        }
    }
}
Copy after login

ChatClient.java

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
                                       
public class ChatClient extends Frame
{
    Socket s = null;
    DataOutputStream dos = null;
    DataInputStream dis = null;
    private boolean bConnected=false;
    TextField tfTxt = new TextField();//输入框
    TextArea taContent = new TextArea();//显示聊天信息框
                                          
                                          
    public static void main(String[] args)
    {
        new ChatClient().lanunchFrame();
    }
                                          
    public void lanunchFrame(){
        setLocation(400,300);
        this.setSize(300, 300);
        add(tfTxt,BorderLayout.SOUTH);
        add(taContent,BorderLayout.NORTH);
        pack();//调整空隙
        this.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e)
            {
                disconnect();
                System.exit(0);
            }
        });
        tfTxt.addActionListener(new TexFileListener());
        setVisible(true);
        connect();
                                              
        new Thread(new RecvThread()).start();
    }
                                          
    public void connect(){
        try
        {
            s= new Socket("127.0.0.1",8881);
            dos=new DataOutputStream(s.getOutputStream());
            dis=new DataInputStream(s.getInputStream());
System.out.println("connected!");
            bConnected =true;
                                                  
        } catch (UnknownHostException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
                                          
    public void disconnect()
    {
        try
        {
            dos.close();
            dis.close();
            s.close();
        } catch (Exception e1)
        {
            e1.printStackTrace();
        }
        /*try
        {
            bConnected = false;  //保证
            recvThread.join();
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
        finally{
            try
            {
                dos.close();
                dis.close();
                s.close();
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
*/
    }
                                          
    private class TexFileListener implements ActionListener{
        public void actionPerformed(ActionEvent e)
        {
            String str=tfTxt.getText().trim();
            //taContent.setText(str);
            tfTxt.setText("");
            try
            {
                dos.writeUTF(str);
                dos.flush();
                //dos.close();
            } catch (IOException e1)
            {
                e1.printStackTrace();
            }
                                                  
        }
    }
    private class RecvThread implements Runnable{
        public void run()
        {
            try
            {
                while (bConnected)
                {
                    String str = dis.readUTF();
                    //System.out.println(str);
                    taContent.setText(taContent.getText()+str+&#39;\n&#39;);
                }
            }
            catch (SocketException e){
                System.out.println("已退出!");
            }
            catch (EOFException e){
                System.out.println("已退出!");
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
Copy after login


For more real-time group chat applet development records, please refer to related articles Follow PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C++ function exceptions and multithreading: error handling in concurrent environments C++ function exceptions and multithreading: error handling in concurrent environments May 04, 2024 pm 04:42 PM

Function exception handling in C++ is particularly important for multi-threaded environments to ensure thread safety and data integrity. The try-catch statement allows you to catch and handle specific types of exceptions when they occur to prevent program crashes or data corruption.

How to implement multi-threading in PHP? How to implement multi-threading in PHP? May 06, 2024 pm 09:54 PM

PHP multithreading refers to running multiple tasks simultaneously in one process, which is achieved by creating independently running threads. You can use the Pthreads extension in PHP to simulate multi-threading behavior. After installation, you can use the Thread class to create and start threads. For example, when processing a large amount of data, the data can be divided into multiple blocks and a corresponding number of threads can be created for simultaneous processing to improve efficiency.

Usage of JUnit unit testing framework in multi-threaded environment Usage of JUnit unit testing framework in multi-threaded environment Apr 18, 2024 pm 03:12 PM

There are two common approaches when using JUnit in a multi-threaded environment: single-threaded testing and multi-threaded testing. Single-threaded tests run on the main thread to avoid concurrency issues, while multi-threaded tests run on worker threads and require a synchronized testing approach to ensure shared resources are not disturbed. Common use cases include testing multi-thread-safe methods, such as using ConcurrentHashMap to store key-value pairs, and concurrent threads to operate on the key-value pairs and verify their correctness, reflecting the application of JUnit in a multi-threaded environment.

How can concurrency and multithreading of Java functions improve performance? How can concurrency and multithreading of Java functions improve performance? Apr 26, 2024 pm 04:15 PM

Concurrency and multithreading techniques using Java functions can improve application performance, including the following steps: Understand concurrency and multithreading concepts. Leverage Java's concurrency and multi-threading libraries such as ExecutorService and Callable. Practice cases such as multi-threaded matrix multiplication to greatly shorten execution time. Enjoy the advantages of increased application response speed and optimized processing efficiency brought by concurrency and multi-threading.

How do PHP functions behave in a multi-threaded environment? How do PHP functions behave in a multi-threaded environment? Apr 16, 2024 am 10:48 AM

In a multi-threaded environment, the behavior of PHP functions depends on their type: Normal functions: thread-safe, can be executed concurrently. Functions that modify global variables: unsafe, need to use synchronization mechanism. File operation function: unsafe, need to use synchronization mechanism to coordinate access. Database operation function: Unsafe, database system mechanism needs to be used to prevent conflicts.

How to deal with shared resources in multi-threading in C++? How to deal with shared resources in multi-threading in C++? Jun 03, 2024 am 10:28 AM

Mutexes are used in C++ to handle multi-threaded shared resources: create mutexes through std::mutex. Use mtx.lock() to obtain a mutex and provide exclusive access to shared resources. Use mtx.unlock() to release the mutex.

Challenges and strategies for testing multi-threaded programs in C++ Challenges and strategies for testing multi-threaded programs in C++ May 31, 2024 pm 06:34 PM

Multi-threaded program testing faces challenges such as non-repeatability, concurrency errors, deadlocks, and lack of visibility. Strategies include: Unit testing: Write unit tests for each thread to verify thread behavior. Multi-threaded simulation: Use a simulation framework to test your program with control over thread scheduling. Data race detection: Use tools to find potential data races, such as valgrind. Debugging: Use a debugger (such as gdb) to examine the runtime program status and find the source of the data race.

Challenges and countermeasures of C++ memory management in multi-threaded environment? Challenges and countermeasures of C++ memory management in multi-threaded environment? Jun 05, 2024 pm 01:08 PM

In a multi-threaded environment, C++ memory management faces the following challenges: data races, deadlocks, and memory leaks. Countermeasures include: 1. Use synchronization mechanisms, such as mutexes and atomic variables; 2. Use lock-free data structures; 3. Use smart pointers; 4. (Optional) implement garbage collection.

See all articles