用Java一次启动2个线程

时间:2018-06-22 10:18:49

标签: java multithreading sockets

这是我第一次在这里问问题。

我正在制作一个应用程序,该应用程序在计算机关闭时向客户端发送短信。

到目前为止,我能够从客户端接收套接字连接,并且当客户端第一次断开连接时,它会发送短信,但是如果Internet断开并且当客户端再次连接时,将启动2个线程而不是一个线程。 >

这是服务器端编码

// Server class
public class server {

public static void main(String[] args) throws IOException {
    // server is listening on port 5056
    ServerSocket ss = new ServerSocket(9000);

    // running infinite loop for getting
    // client request
    while (true) {
        Socket s = null;

        try {
            // socket object to receive incoming client requests
            s = ss.accept();

            System.out.println("A new client is connected : " + s);

            // obtaining input and out streams
            DataInputStream dis = new DataInputStream(s.getInputStream());
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());

            System.out.println("Assigning new thread for this client");

            // create a new thread object
            Thread t = new ClientHandler(s, dis, dos);

            // Invoking the start() method
            t.start();

        } catch (Exception e) {
            s.close();
            e.printStackTrace();
        }
    }
}
}

// ClientHandler class
class ClientHandler extends Thread {

DateFormat fordate = new SimpleDateFormat("yyyy/MM/dd");
DateFormat fortime = new SimpleDateFormat("hh:mm:ss");
final DataInputStream dis;
final DataOutputStream dos;
final Socket s;
public String received;
public static String mobile, left, name, uuid, smsrem, smsremafter;
public static int length, firstchar, length2, intsmsrem, intsmsremafter;
public static String receivedd;

// Constructor
public ClientHandler(Socket s, DataInputStream dis, DataOutputStream dos) {
    this.s = s;
    this.dis = dis;
    this.dos = dos;
}

@Override
public void run() {
    String received;
    String toreturn;
    while (true) {
        try {

            // Ask user what he wants
//i dont want to ask
            // receive the answer from client
            received = dis.readUTF();
            System.out.println(received);
            if (received.equals("Exit")) {
                System.out.println("Client " + this.s + " sends exit...");
                System.out.println("Closing this connection.");
                this.s.close();
                System.out.println("Connection closed");
                break;
            }

            receivedd = received;
            mobile = received.substring(0, 10);
            length = received.length();
            left = received.substring(11, length);
            firstchar = left.indexOf("~");
            length2 = left.length();
            name = left.substring(0, firstchar);
            uuid = left.substring(firstchar + 1, length2);

            System.out.println(mobile);
            System.out.println(name);
            System.out.println(uuid);
        } catch (IOException e) {
            try {
                //Client disconnect

                System.out.println("sms sent to " + mobile);
                System.out.println("sms decrease for" + uuid);
                s.close();
                break;
            } catch (IOException ex) {
                Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    try {
        // closing resources
        this.dis.close();
        this.dos.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

这是客户端代码。

              // Client class
       public class client 
       {
      public static void main(String[] args) throws IOException 
{
      String home = System.getProperty("user.dir");
    String name = new String(Files.readAllBytes(Paths.get(home + "\\miningmajdur\\common\\tamilper.txt")));
    String mobile = new String(Files.readAllBytes(Paths.get(home + "\\miningmajdur\\common\\tamilnokud.txt")));
    String uid = new String(Files.readAllBytes(Paths.get(home + "\\miningmajdur\\common\\duke.txt")));
    try
    {
        Scanner scn = new Scanner(System.in);

        // getting localhost ip
        InetAddress ip = InetAddress.getByName("localhost");

        // establish the connection with server port 5056
        Socket s = new Socket(ip, 9000);

        // obtaining input and out streams
        DataInputStream dis = new DataInputStream(s.getInputStream());
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());

        // the following loop performs the exchange of
        // information between client and client handler
        while (true) 
        {

             String tosend = ("2222222222" + "~" + name + "~" + uid);
                dos.writeUTF(tosend);


            // If client sends exit,close this connection 
            // and then break from the while loop
            if(tosend.equals("Exit"))
            {
                System.out.println("Closing this connection : " + s);
                s.close();
                System.out.println("Connection closed");
                break;
            }

            // printing date or time as requested by client
            String received = dis.readUTF();
            System.out.println(received);
        }

        // closing resources
        scn.close();
        dis.close();
        dos.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

这是多线程上的单连接开始的地方

A new client is connected : Socket[addr=/192.168.56.1,port=51447,localport=9000]
Assigning new thread for this client
no of threads ---------------3
A new client is connected : Socket[addr=/192.168.56.1,port=51446,localport=9000]
Assigning new thread for this client
no of threads ---------------4
A new client is connected : 
Socket[addr=/192.168.56.1,port=51448,localport=9000]
Assigning new thread for this client
no of threads ---------------5
A new client is connected : Socket[addr=/192.168.56.1,port=51450,localport=9000]
Assigning new thread for this client

2 个答案:

答案 0 :(得分:1)

您需要在服务器端维护一些列表,并且每次收到连接请求时都需要检查重复的请求

答案 1 :(得分:0)

我的东西起作用了。

我使用Thread.interrupt通过将线程名称放入向量中来关闭任何现有线程,并检查是否存在任何现有线程以及是否存在关闭其他线程。