Java多线程聊天应用|集1(服务器端.java)在集2中讨论

Java 多线程聊天应用程序 |第 1 集(服务器端编程)

原文:.geesforgeks.org/multithreading-chat-application-setting-1/

先决条件:在 Socket 编程中引入线程 在上一篇文章中,创建了一个简单的日期时间服务器,它使用线程同时处理多个用户请求。它解释了网络编程中线程的基本概念。稍作改动,同样的概念可以用来增强上述感知,创建一个类似于 facebook messenger、whatsapp 等的聊天应用程序。下面的文章将详细解释这些应用程序的实现、限制和解决方案。在本集中,我们将在第 2 集中讨论服务器端编程(Server.java)和客户端编程(Client.java)。

服务器端编程(Server.java)

1。服务器类:主服务器实现简单,和上一篇类似。以下几点将有助于理解服务器强制执行:

服务器运行一个无限循环以继续接受传入的请求。当请求到来时,它会分配一个新的线程来处理通信部分。服务器还将客户端名称存储在向量中以跟踪连接的设备。向量存储当前请求对应的线程对象。助手类使用此向量来查找要传递消息的收件人的姓名。因为这个向量包含所有流,处理程序类可以使用它来成功地将消息传递给特定的客户端。调用 start() 方法。

2。 ClientHandler 类:和上一篇文章类似,我们创建了一个帮助类来处理各种类型的请求。这一次应用编程接口和套接字,对于套接字和流,我们引入了一个名称变量。这将保存连接到服务器的客户端的名称。以下几点有助于理解ClientHandler的实现:

message # recipient

Java(一种专门用于创建网站的计算机语言)

// Java implementation of  Server side
// It contains two classes : Server and ClientHandler
// Save file as Server.java
import java.io.*;
import java.util.*;
import java.net.*;
// Server class
public class Server
{
    // Vector to store active clients
    static Vector<ClientHandler> ar = new Vector();
    // counter for clients
    static int i = 0;
    public static void main(String[] args) throws IOException
    {
        // server is listening on port 1234
        ServerSocket ss = new ServerSocket(1234);
        Socket s;
        // running infinite loop for getting
        // client request
        while (true)
        {
            // Accept the incoming request
            s = ss.accept();
            System.out.println("New client request received : " + s);
            // obtain input and output streams
            DataInputStream dis = new DataInputStream(s.getInputStream());
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            System.out.println("Creating a new handler for this client...");
            // Create a new handler object for handling this request.
            ClientHandler mtch = new ClientHandler(s,"client " + i, dis, dos);
            // Create a new Thread with this object.
            Thread t = new Thread(mtch);
            System.out.println("Adding this client to active client list");
            // add this client to active clients list
            ar.add(mtch);
            // start the thread.
            t.start();
            // increment i for new client.
            // i is used for naming only, and can be replaced
            // by any naming scheme
            i++;
        }
    }
}
// ClientHandler class
class ClientHandler implements Runnable
{
    Scanner scn = new Scanner(System.in);
    private String name;
    final DataInputStream dis;
    final DataOutputStream dos;
    Socket s;
    boolean isloggedin;
    // constructor
    public ClientHandler(Socket s, String name,
                            DataInputStream dis, DataOutputStream dos) {
        this.dis = dis;
        this.dos = dos;
        this.name = name;
        this.s = s;
        this.isloggedin=true;
    }
    @Override
    public void run() {
        String received;
        while (true)
        {
            try
            {
                // receive the string
                received = dis.readUTF();
                System.out.println(received);
                if(received.equals("logout")){
                    this.isloggedin=false;
                    this.s.close();
                    break;
                }
                // break the string into message and recipient part
                StringTokenizer st = new StringTokenizer(received, "#");
                String MsgToSend = st.nextToken();
                String recipient = st.nextToken();
                // search for the recipient in the connected devices list.
                // ar is the vector storing client of active users
                for (ClientHandler mc : Server.ar)
                {
                    // if the recipient is found, write on its
                    // output stream
                    if (mc.name.equals(recipient) && mc.isloggedin==true)
                    {
                        mc.dos.writeUTF(this.name+" : "+MsgToSend);
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try
        {
            // closing resources
            this.dis.close();
            this.dos.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}

输出:

New client request received : Socket[addr=/127.0.0.1,port=61818,localport=1234]
Creating a new handler for this client...
Adding this client to active client list
New client request received : Socket[addr=/127.0.0.1,port=61819,localport=1234]
Creating a new handler for this client...
Adding this client to active client list

限制:即使是上面的服务器实现也能处理大多数情况,但内部定义的方式也存在一些缺陷。

客户端程序(Client.java)与后面的文章有很大不同应用编程接口和套接字,将在本系列的第 2 部分中讨论。

相关文章:多线程聊天应用程序 |第 2 集

本文由 Rishab Mahesh 提供。如果您喜欢 GeeksforGeeks 并希望做出贡献,您还可以使用 write.geeksforgeeks.org 撰写文章或将您的文章发送至 review-team@geeksforgeeks.org。查看您的文章出现在极客博客主页上并帮助其他极客。如果您发现任何不准确的地方,或者如果您想分享有关之前讨论的主题的更多信息,请发表评论。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悟空资源网 网站程序 Java多线程聊天应用|集1(服务器端.java)在集2中讨论 https://www.wkzy.net/game/8238.html

常见问题

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务