停止Java线程

时间:2018-11-19 22:08:28

标签: java final

我为服务器和客户端编写了一个Java应用程序。我想做的是当用户输入单词“ logout”时停止Client的应用程序(及其所有线程)。我已经尽力在这里找到所有想要的东西。请发送帮助!

这是我的Client.java代码

    package client;

//Java implementation for multithreaded chat client 
//Save file as Client.java 

import java.io.*; 
import java.net.*; 
import java.util.Scanner; 

public class Client extends Thread
{ 

    final static int ServerPort = 1234; 
    private volatile static boolean running = true;

    public static void main(String args[]) throws UnknownHostException, IOException 
    { 
        Scanner scn = new Scanner(System.in); 

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

        // establish the connection 
        Socket s = new Socket(ip, ServerPort); 

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

        // sendMessage thread 
        Thread sendMessage = new Thread(new Runnable() 
        { 
            @Override
            public void run() { 
                while (running) { 

                    // read the message to deliver.
                    try {  
                        String msg = scn.nextLine(); 
                        if(msg == "logout") {
                            running = false;
                            dis.close();
                            dos.close();
                            scn.close();
                            s.close();
                            Thread.currentThread().interrupt();
                            break;
                        }
                        dos.writeUTF(msg);
                    }
                    catch (IOException e) { 
                        if(!running) {
                            System.out.println("Closing...");
                            System.exit(0);
                        }
                } 
            } }
        }); 

        // readMessage thread 
        Thread readMessage = new Thread(new Runnable() 
        { 
            @Override
            public void run() { 

                while (running) { 
                    // read the message sent to this client 
                    try { 
                        String msg = dis.readUTF();
                        if(sendMessage.isInterrupted()) {
                            running = false;
                            dis.close();
                            dos.close();
                            scn.close();
                            s.close();
                            Thread.currentThread().interrupt();
                            break;
                        }
                        System.out.println(msg);

                    } catch (IOException e) { 
                        if(!running) {
                            System.out.println("Closing...");
                            System.exit(0);
                        }
                    } 
                } 
            } 
        }); 

        sendMessage.start(); 
        readMessage.start(); 

    } 
}

这是我的Server.java

package server;

//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  
{
 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(); 


             if(received.equals("logout")){ 
                 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(); 
         this.s.close();
         this.isloggedin=false;

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

代码参考:Multithread GroupChat 1                 Multithread GroupChat 2

1 个答案:

答案 0 :(得分:-1)

不要将字符串与==但与equals()进行比较。 msg == "logout"应该是msg.equals("logout")

相关问题