繁体   English   中英

如何确保每个当前运行的客户端的唯一ID以及如何确保每个ID匹配模式

[英]how to ensure unique id for each currently running client as well as ensure that each id matches pattern

可以这么说,您有一个使用Java的联网程序,其中服务器一次为多个客户端提供服务,每个客户端访问其信息的方式只是键入ID。 在服务器为客户端启动线程之前,您希望它确保客户端程序开始运行后用户输入的ID尚未被当前正在运行的线程使用,并且该ID与特定模式(例如4位数)。 我采用的方法是让服务器类在执行任何操作之前为当前正在运行的线程的id声明并初始化一个arraylist,使用正则表达式检查id是否为4位数字,如果是,则为然后检查id是否在arraylist中,如果不是,则线程可以开始。 代码如下所示:

   while(true)
  {
     ClientWorker w;
     try
     {
        w = new ClientWorker(server.accept());
        String validid = w.accountnumber;
        if(validid.matches("\\d[4]"))
        {
             if(!currentusers.contains(validid))
             {
                currentusers.add(validid);
                Thread t = new Thread(w);
                t.start();
             }
             else
             {
                 System.out.println("Already in session");
             }
        }
        else
        {
            System.out.println("not a valid id");
        }
 }

问题是我的目标都没有实现,只会给以前运行的程序带来错误:无论我输入什么id,客户都会继续进行,并问我要进行哪些交易。 然后,如果我尝试执行任何操作,则服务器程序将崩溃,并在我尝试匹配if语句中的正则表达式时以及在告诉服务器侦听main方法中与客户端套接字对应的端口时给我空指针异常。 我认为问题在于我无法在线程启动之前找出获取客户端ID的方法,因为在我看来,线程必须在用户可以键入其ID之前启动,这会产生一个圆圈我必须摆正。 谁能帮我这个忙吗? PS:clientworker类接受套接字作为其构造函数的参数,并将其分配给已经声明的套接字引用,以防万一。

该算法应为:

while (true)
    accept a new client
    start a thread to communicate with the client

线程应该执行以下操作:

read the ID sent by the client
check if it's valid and add it to a set of IDs if not already present
if invalid or already present
    send an error message to the client
    stop running
else 
    continue the conversation with the client. 
    once the conversation ends, in a finally block, remove the ID from the set of IDs

您应该使用HashSet而不是List,因为它在查找(O(1))时要快得多,并且应确保方法checkIfIdPresentAndIfItDoesntThenAddTheId()removeId()正确同步,因为该集可以由多个线程访问。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM