简体   繁体   中英

Multi Threads Socket Java

My client:

class Read_ChatClient extends Thread{

private static Socket client;
private  String user;
static ArrayList<SingleChatF> chatFrames = new ArrayList<>();

public Read_ChatClient(Socket client, String username) {
    this.client = client;
    this.user = username;
}

public void checkAddNewFrame(String sourceName, String desName, String mess){
    boolean exitFrame = false;
    int index = 0;
    for(SingleChatF frame: chatFrames) {
        System.out.println(index + "; " + frame.getSourceName() + "; " + frame.getDestName());
        if (frame.Match(sourceName, desName)) {
            frame.gettxtchatall().append(mess + "\n");
            System.out.println("Founded frame: " + sourceName + "; " + desName);
            exitFrame = true;
            break;
        };
        index++;
    }
    if(!exitFrame) {
        SingleChatF newFrame = new SingleChatF(this.client, sourceName, desName);
        newFrame.setVisible(true);
        newFrame.gettxtchatall().append(mess + "\n");
        chatFrames.add(newFrame);
        System.out.println("Created new frame: " + sourceName + "; " + desName);
    }

}
@Override
public void run(){
    System.out.println(new Date().getTime() + " - Read_ChatClient");
    DataInputStream dis = null;
    try {
        dis = new DataInputStream(client.getInputStream());
        System.out.println(" - Read_ChatClient client.getInputStream() OK");
        while(true) {
            System.out.println(" - Read_ChatClient......");
            String sms = dis.readUTF();
            System.out.println(" - Read_ChatClient.sms: "+sms);
            if (sms.contains("login_successed")){
                System.out.println(" - Read_ChatClient: Join()");
                String[] info = sms.split(";");
                String username = info[1];
                String[] onlineuserList = info[2].split(",");
                if (username.equalsIgnoreCase(user)) {
                    MultiThreads_LoginClient.setLoginF(false);
                    MultiThreads_LoginClient.chatFrame = new ChatF(user, client);
                    MultiThreads_LoginClient.chatFrame.setVisible(true);
                    JTable OnlineTab = MultiThreads_LoginClient.chatFrame.getjtableonlineuser();
                    DefaultTableModel model = (DefaultTableModel) OnlineTab.getModel();
                    for (String name : onlineuserList) {
                       model.addRow(new String[]{name});
                    }
                }else if(!username.equalsIgnoreCase(user)){
                     MultiThreads_LoginClient.chatFrame.getjtableonlineuser().setModel(new DefaultTableModel(null,new String[]{"Online Users"}));
                    for (String name : onlineuserList) {
                        JTable OnlineTab = MultiThreads_LoginClient.chatFrame.getjtableonlineuser();
                        DefaultTableModel model = (DefaultTableModel) OnlineTab.getModel();
                        model.addRow(new String[]{name}); 
                    }
                    MultiThreads_LoginClient.chatFrame.gettxtchatall().append(username+" da ket noi\n");
                }
            } else if (sms.contains("login_failed;")) {
                JOptionPane.showMessageDialog(null, "Login Failed");
            } else if (sms.contains("user_actived")) {
                JOptionPane.showMessageDialog(null, "User's activing");
            }else if(sms.contains("updateOnlineUserList")){
                String[] list = sms.split(":");
                String[] newList = list[1].split(",");
                MultiThreads_LoginClient.chatFrame.getjtableonlineuser().setModel(new DefaultTableModel(null,new String[]{"Online Users"}));
                for (String name : newList) {
                    JTable OnlineTab = MultiThreads_LoginClient.chatFrame.getjtableonlineuser();
                    DefaultTableModel model = (DefaultTableModel) OnlineTab.getModel();
                    model.addRow(new String[]{name});
                }
                System.out.println("updateOnlineUserList:"+sms);
            }else if(sms.contains("chatPrivate")){
                //{ChatPrivate}:{Source_name}:{des_name}:{mess}:{host:port}
                System.out.println("ClientRead_chatPrivate: " + sms);
                String[] content = sms.split(";");
                String sourceName = content[1];
                String desName = content[2];
                String mess = content[3];
                checkAddNewFrame(desName, sourceName, mess);
            }else if(sms.contains("AlertAlert_SendFilesToClient")){
                System.out.println("AlertAlert_SendFilesToClient");
                currentThread().wait();
                Read_FileClient rf = new Read_FileClient(client);
                rf.start();
            }else{
                MultiThreads_LoginClient.chatFrame.gettxtchatall().append("\n" + sms);
                System.out.println(sms);
            }
        }
    } catch (Exception e) {
       try {
           currentThread().wait();
           Read_FileClient rf = new Read_FileClient(client);
           rf.start();
           //dis.close();
        } catch (InterruptedException ex) {
            Logger.getLogger(Read_ChatClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}}

My Server:

class Read_ChatServer extends Thread{
private static Socket socket;
private static SingleChatFrame_SV singlechatFrame;
public static void setsocket(Socket socket){
    Read_ChatServer.socket = socket;
}

public Read_ChatServer(Socket client) {
    this.socket = client;
}

@Override
public void run(){
    System.out.println("Read_ChatServer");
    DataInputStream dis = null;
    DataOutputStream dos = null;
    try {
        System.out.println("Checking socket.getInputStream()");
        dis = new DataInputStream(socket.getInputStream());
        System.out.println("OK socket.getInputStream()");
        while (true) {
            String sms = dis.readUTF();
            System.out.println(" - Read_ChatServer: " + sms);
            if (sms.contains("Login_Requiere")) {
                //{Login_Requiere};{username};{password}
                try {
                    dis = new DataInputStream(socket.getInputStream());
                    dos = new DataOutputStream(socket.getOutputStream());
                    System.out.println("Trying login for user " + sms);
                    String[] contents = sms.split(";");

                    String info[] = sms.split(";");//info[1]: username  - info[2]:pass
                    Connection con = DBConnection.getConnection();
                    String query = "Select *from `info` where `user`=? AND `pw`=?";
                    PreparedStatement pst;
                    ResultSet rs;
                    try {
                        pst = con.prepareStatement(query);
                        pst.setString(1, info[1]);
                        pst.setString(2, info[2]);
                        rs = pst.executeQuery();
                        if (rs.next()) {
                            // login;{success: true, onlineuser: ["", ""]}
                            // chat;
                            if (!MultiThreads_LoginServer.checkuserexits(info[1])) {
                                accountinfo temp = new accountinfo(socket, info[1]);
                                MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("Da ket noi " + info[1] + "\n");
                                System.out.println("Da ket noi " + socket);
                                MultiThreads_LoginServer.accountinfoList.add(temp);
                                showonlineuser();
                                String statusString = "login_successed;" + info[1] + ";" + MultiThreads_LoginServer.convertoString();
                                BroadCastUserListToAllClients wu = new BroadCastUserListToAllClients(statusString);
                                wu.start();
                            } else {
                                dos.writeUTF("user_actived; ; ");
                            }

                        } else {

                            dos.writeUTF("login_failed; ; ");
                            //dos.flush();
                        }
                    } catch (SQLException ex) {
                        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    DBConnection.closeConnection(con);
                    MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("User: " + info[1] + "\tPass: " + info[2] + "\n");

                } catch (Exception e) {
                    System.out.println(" - Error Read_LoginServer: " + e.getMessage());
                    try {
                        dis.close();
                        dos.close();
                        socket.close();
                    } catch (IOException ex) {
                        Logger.getLogger(Read_LoginServer.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }else if (sms.contains("exit")) {
                String[] exitInfo = sms.split(":");
                String notify = "Ngat ket noi voi : " + exitInfo[1]+"\n";
                try {
                    MultiThreads_LoginServer.remove_user(exitInfo[1]);
                    if (MultiThreads_LoginServer.accountinfoList.isEmpty()) {
                        MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("No User Online!");
                    } else {
                        showonlineuser();
                        MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append(notify + "\n");
                        System.out.println(" - Read_ChatServer: " + notify);
                        for (accountinfo item : MultiThreads_LoginServer.accountinfoList) {
                            dos = new DataOutputStream(item.socket.getOutputStream());
                            dos.writeUTF(notify);
                            //dos.flush();
                        }
                    }
                    String currentList = convertoString();
                    BroadCastUserListToAllClients broad = new BroadCastUserListToAllClients("updateOnlineUserList: " + currentList);
                    broad.start();
                } catch (Exception e) {
                    showonlineuser();
                    MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append(notify + "\n");
                    MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("No User Online!");
                }

            } else if(sms.contains("chatPrivate")){
                System.out.println("server_chatPrivate: "+ sms);
                //{ChatPrivate};{Source_name};{des_name};{mess}
                String[] content = sms.split(";");
                String s_name = content[1];
                String d_name = content[2];
                if(d_name.equalsIgnoreCase("Server")){
                   //
                }else{
                    for(accountinfo item:MultiThreads_LoginServer.accountinfoList){
                    if(item.username.equalsIgnoreCase(d_name)){
                        dos = new DataOutputStream(item.socket.getOutputStream());
                        dos.writeUTF(sms);
                    }
                }
                }

            }else if(sms.contains("Alert_SendFiles")){
                System.out.println("Alert_SendFiles");
                String[] content = sms.split(":");
                String des_name = content[1];

                AlertAlert_SendFilesToClient alert = new AlertAlert_SendFilesToClient(des_name);
                alert.start();
                Thread.sleep(1000);
                System.out.println("-Alert_SendFiles: pass alert");
                currentThread().wait();
                Read_FileServer rf = new Read_FileServer(socket);
                rf.start();


            }else{
                MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append(sms + "\n");
                for (accountinfo item : MultiThreads_LoginServer.accountinfoList) {

                     dos = new DataOutputStream(item.socket.getOutputStream());
                    dos.writeUTF(sms);
                    //dos.flush();
                }

            }

        }

    } catch (Exception e) {
        System.out.println("No user online!");
        System.out.println(" - Error Read_ChatServer: " + e.getMessage());
        try {
            dis.close();
            //dos.close();

        } catch (IOException ex) {
            System.out.println(" - Error Read_ChatServer: " + ex.getMessage());
            Logger.getLogger(Read_ChatServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}}

My class Send file:

class Write_SendFiles extends Thread{
private Data_file data;
private Socket client;
public Write_SendFiles(Data_file data,Socket client) {
  this.data = data;
  this.client = client;
}

@Override
public void run() {
    System.out.println("Write_SendFiles");
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(client.getOutputStream());
         System.out.println("-Write_SendFiles:"+data.getfilename());
        oos.writeObject(data);

        System.out.println("-Write_SendFiles: pass send file");
    } catch (IOException ex) {
        /*try {
            oos.close();
        } catch (IOException ex1) {
             System.out.println("-Write_SendFiles Err:"+ex.getMessage());
            Logger.getLogger(Write_SendFiles.class.getName()).log(Level.SEVERE, null, ex1);
        }*/
          System.out.println("-Write_SendFiles Err:"+ex.getMessage());
        Logger.getLogger(Write_SendFiles.class.getName()).log(Level.SEVERE, null, ex);
    }
}   }

class Read_FileClient extends Thread{

private Socket client;

public Read_FileClient(Socket client) {
    this.client = client;
}

@Override
public void run() {
    System.out.println("Client file");
    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(client.getInputStream());
        System.out.println("-Server file: pass new obj");
        try {
            Data_file datafile = (Data_file) ois.readObject();
            System.out.println("-Server file:read file successfully");
            boolean exitingChatFrame_file = false;
            for (SingleChatF single : Read_ChatClient.chatFrames) {
                exitingChatFrame_file = single.Match(datafile.getdes_name(), datafile.getdes_name());
                System.out.println("File - Finding frame: Source=" + datafile.getdes_name() + "; Dest=" + datafile.getdes_name() + "; " + exitingChatFrame_file);
                if (exitingChatFrame_file) {
                    JList FilesTranfer = single.getjlisttranfer();
                    DefaultListModel model = new DefaultListModel();
                    FilesTranfer.setModel(model);
                    model.addElement(datafile);
                    System.out.println("Founded");
                    single.gettxtchatall().append("Getting file...");
                    break;
                }
            }
            if (!exitingChatFrame_file) {
                System.out.println("ClientRead_chatPrivate: not active");
                SingleChatF newFrame = new SingleChatF(this.client, datafile.getdes_name(), datafile.getdes_name());
                newFrame.setVisible(true);
                JList FilesTranfer = newFrame.getjlisttranfer();
                DefaultListModel model = new DefaultListModel();
                FilesTranfer.setModel(model);
                model.addElement(datafile);
                chatFrames.add(newFrame);
                newFrame.gettxtchatall().append("Getting file...");
            }

            //client.close();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Read_ChatClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (IOException ex) {
        Logger.getLogger(Read_FileClient.class.getName()).log(Level.SEVERE, null, ex);
    }

}}

My Server read file:

class Read_FileServer extends Thread{
private Socket client;

public Read_FileServer(Socket client) {
    this.client = client;
}

@Override
public void run() {
    System.out.println("Server Read_FileServer");
    ObjectInputStream ois = null;
    ObjectOutputStream oos = null;
    try {
        ois = new ObjectInputStream(client.getInputStream());
        try {
            Data_file datafile = (Data_file)ois.readObject();
            System.out.println("-Server Read_FileServer: read file successfully");
            for(accountinfo item : MultiThreads_LoginServer.accountinfoList){
                if(item.username.equalsIgnoreCase(datafile.getdes_name())){
                    oos = new ObjectOutputStream(item.socket.getOutputStream());
                    oos.writeObject(datafile);
                }
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Read_FileServer.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (IOException ex) {
        try {
            ois.close();
            oos.close();

        } catch (IOException ex1) {
            Logger.getLogger(Read_FileServer.class.getName()).log(Level.SEVERE, null, ex1);
        }

        Logger.getLogger(Read_FileServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}

But now i have the function is send file. So i have to use ObjectInputStream and Object OutputStream .The problems is 2 type difference between DataInputStream,DataOutputStream and ObjectInputStream,OutputStream.How can i put thread of ObjectInputStream and ObjectOutputStreadm to my class. thanks you!

try (DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStreamdos = new DataOutputStream(socket.getOutputStream())){
                    System.out.println("Trying login for user " + sms);
                    String[] contents = sms.split(";");
                    String info[] = sms.split(";");//info[1]: username  - info[2]:pass
                    Connection con = DBConnection.getConnection();
                    String query = "Select *from `info` where `user`=? AND `pw`=?";
                    PreparedStatement pst;
                    ResultSet rs;
                    try {
                        pst = con.prepareStatement(query);
                        pst.setString(1, info[1]);
                        pst.setString(2, info[2]);
                        rs = pst.executeQuery();
                        if (rs.next()) {
                            // login;{success: true, onlineuser: ["", ""]}
                            // chat;
                            if (!MultiThreads_LoginServer.checkuserexits(info[1])) {
                                accountinfo temp = new accountinfo(socket, info[1]);
                                MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("Da ket noi " + info[1] + "\n");
                                System.out.println("Da ket noi " + socket);
                                MultiThreads_LoginServer.accountinfoList.add(temp);
                                showonlineuser();
                                String statusString = "login_successed;" + info[1] + ";" + MultiThreads_LoginServer.convertoString();
                                BroadCastUserListToAllClients wu = new BroadCastUserListToAllClients(statusString);
                                wu.start();
                            } else {
                                dos.writeUTF("user_actived; ; ");
                            }

                        } else {

                            dos.writeUTF("login_failed; ; ");
                            //dos.flush();
                        }
                    } catch (SQLException ex) {
                        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    DBConnection.closeConnection(con);
                    MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("User: " + info[1] + "\tPass: " + info[2] + "\n");

                } catch (Exception e) {
                    System.out.println(" - Error Read_LoginServer: " + e.getMessage());
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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