App下載

使用Java多線(xiàn)程來(lái)實(shí)現(xiàn)多人聊天室 附實(shí)例代碼

流年絮語(yǔ) 2021-08-09 13:47:45 瀏覽數(shù) (3161)
反饋

1.前言

程序?qū)崿F(xiàn)基于星型結(jié)構(gòu)(服務(wù)器接收來(lái)自各個(gè)客戶(hù)端發(fā)送的信息,然后將信息傳遞給其他客戶(hù)端界面并在其他客戶(hù)端界面顯示發(fā)送的信息)

在這里插入圖片描述

2.類(lèi)圖

在這里插入圖片描述

3.代碼

客戶(hù)端代碼:

package netProgram;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketAddress;

public class Client implements ScreenInputInterface{
    private SocketHandler socketHandler;

    public void start(){
        new Thread(new ScreenInputRunIns(this)).start();
        try {
            socketHandler =   new SocketHandler(new Socket("127.0.0.1",666),null);
            new Thread(socketHandler).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void send(String msg) {
        socketHandler.sendMsg(msg);
    }

    /*    @Override
    public void send(String msg, SocketAddress address) {
        socketHandler.sendMsg(msg);
    }*/
}

服務(wù)端代碼:

package netProgram;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

public class Server implements ScreenInputInterface{
    private List<SocketHandler> clients = new ArrayList<>();
    private ServerSocket serverSocket;

    public void start(){
//        new Thread(new ScreenInputRunIns(this)).start();
        try {
            serverSocket = new ServerSocket(666);
            while (true){
                SocketHandler socketHandler = new SocketHandler(serverSocket.accept(),this);
                clients.add(socketHandler);
                System.out.println(socketHandler.getSocket().getRemoteSocketAddress()+"進(jìn)入聊天系統(tǒng)");
                new Thread(socketHandler).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void send(String msg) {
        for (SocketHandler s:clients) {
            s.sendMsg(msg);
        }
    }

    /*    @Override
    public void send(String msg, SocketAddress address) {
        for (SocketHandler s:clients) {
            if (s.getSocket().getRemoteSocketAddress().equals(address)){
                continue;
            }
            s.sendMsg(msg);
        }
    }*/

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

屏幕輸入信息接口:

package netProgram;

import java.net.SocketAddress;

public interface ScreenInputInterface {
    void send(String msg);
//    void send(String msg, SocketAddress address);
}

用于各個(gè)端口輸入信息的創(chuàng)建的線(xiàn)程對(duì)象:

package netProgram;

import java.util.Scanner;

public class ScreenInputRunIns implements Runnable{
    private ScreenInputInterface screenInputInterface;
    private Scanner input = new Scanner(System.in);

    public ScreenInputRunIns(ScreenInputInterface screenInputInterface) {
        this.screenInputInterface = screenInputInterface;
    }

    @Override
    public void run() {//屏幕實(shí)時(shí)輸入
        while (true){
            String msg = input.nextLine();
//            screenInputInterface.send(msg,null);
            screenInputInterface.send(msg);
        }
    }
}

套接字處理器(用于傳輸數(shù)據(jù):實(shí)際發(fā)送信息到輸出流并實(shí)時(shí)監(jiān)聽(tīng)各個(gè)端口的輸入且負(fù)責(zé)顯示):

package netProgram;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketHandler implements Runnable{
    private String clientName;
    private Socket socket;
    private PrintWriter writer;
    private Server server;

    public SocketHandler(Socket socket,Server server) throws IOException {
        this.socket = socket;
        this.server = server;
        clientName  = "<"+socket.getLocalSocketAddress()+">";
        writer = new PrintWriter(this.socket.getOutputStream());
    }

    public Socket getSocket() {
        return socket;
    }

    public void sendMsg(String msg){
        if (server!=null) writer.println(msg);
        else writer.println(clientName+":"+msg);
        writer.flush();
    }

    @Override
    public void run() {
        while(true){//監(jiān)聽(tīng)輸入流的輸入
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String receiveMsg = null;
                System.out.println();
                if ((receiveMsg = reader.readLine())!=null&&!(receiveMsg.equals(""))){
                    if (server!=null){
//                        server.send(receiveMsg,socket.getRemoteSocketAddress());
                        server.send(receiveMsg);
                    }else {
                        System.out.println(receiveMsg);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

負(fù)責(zé)啟動(dòng)的各個(gè)端口的客戶(hù)端代碼:

package netProgram;

public class ClientLinked {
    public static void main(String[] args) {
        new Client().start();
    }
}
package netProgram;

public class ClientLinked1 {
    public static void main(String[] args) {
        new Client().start();
    }
}
package netProgram;

public class ClientLinked2 {
    public static void main(String[] args) {
        new Client().start();
    }
}

服務(wù)端啟動(dòng)代碼在服務(wù)端類(lèi)的main方法中。

到此本篇關(guān)于使用Java多線(xiàn)程來(lái)實(shí)現(xiàn)多人聊天室的文章就介紹結(jié)束了,想要了解更多相關(guān)java多線(xiàn)程的其他應(yīng)用內(nèi)容,請(qǐng)搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章。希望本篇文章能夠幫助大家對(duì)于Java多線(xiàn)程的理解,也希望大家以后多多支持!

0 人點(diǎn)贊