多个客户端同时访问服务器

时间:2014-03-29 15:13:58

标签: java multithreading

我正在登录屏幕,现在说我们有两个用户名:amit和ajay以及他们的密码:“pass”和“word”。现在我想要假设他们是在同一系统上打开的两个桌面应用程序.I希望多个客户端同时访问服务器。

意思是说在一个登录屏幕上amit输入用户名,然后他的线程应该睡觉,在第二个登录屏幕让ajay输入他的用户名然后amit将再次输入他的密码,然后ajay输入他的密码。如何在java中执行?请帮忙。

2 个答案:

答案 0 :(得分:5)

在这里,我将与您分享一个不错的客户端服务器身份验证应用程序,其中有一台服务器根据您的要求使用TCP协议与多个客户端进行通信。

答案:

  

此处每个客户端都与服务器连接在一个单独的线程中,该线程包含有关客户端的所有信息。它将解决您的并发问题。


请参阅内联评论以获得更多说明。

注意:替换LiveChatClient.java文件中的主机名,然后在1234号端口运行此程序

运行程序的步骤:

  • 首次运行LiveChatServer仅限一次
  • 然后为多个客户端运行LiveChatClient任意多个

以下是同一上下文中的另一个示例。请查看 Java Server with Multiclient communication.


<强> Opcode.java:

用于设置客户端 - 服务器通信协议的操作代码

/**************** an interface to define different operation code **************/

public interface Opcode {
    int CLIENT_USERNAME = 1;
    int CLIENT_INVALID_USERNAME = 2;
    int CLIENT_PASSWORD = 3;
    int CLIENT_INVALID_PASSWORD = 4;
    int CLIENT_CONNECTED = 5;
}

<强> LiveChatServer.java:

控制多个客户端的单个服务器

/************************ Live Chat Server *******************/

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedHashMap;

public class LiveChatServer {

    // Connection state info
    private static LinkedHashMap<String, ClientThread> clientInfo = new LinkedHashMap<String, ClientThread>();

    // TCP Components
    private ServerSocket serverSocket;

    // Main Constructor
    public LiveChatServer() {

        startServer();// start the server
    }

    public void startServer() {
        String port = "1234";

        try {
            // in constractor we are passing port no, back log and bind address whick will be local
            // host
            // port no - the specified port, or 0 to use any free port.
            // backlog - the maximum length of the queue. use default if it is equal or less than 0
            // bindAddr - the local InetAddress the server will bind to

            int portNo = Integer.valueOf(port);
            serverSocket = new ServerSocket(portNo, 0, InetAddress.getLocalHost());
            System.out.println(serverSocket);

            System.out.println(serverSocket.getInetAddress().getHostName() + ":"
                    + serverSocket.getLocalPort());

            while (true) {
                Socket socket = serverSocket.accept();
                new ClientThread(socket);
            }
        } catch (IOException e) {
            System.out.println("IO Exception:" + e);
            System.exit(1);
        } catch (NumberFormatException e) {
            System.out.println("Number Format Exception:" + e);
            System.exit(1);
        }
    }

    public static HashMap<String, ClientThread> getClientInfo() {
        return clientInfo;
    }

    // *********************************** Main Method ********************

    public static void main(String args[]) {
        new LiveChatServer();
    }

}

<强> LiveChatClient.java:

连接到单个服务器的多个客户端

/************************ Live Chat Client *******************/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;

public class LiveChatClient {
    private String chatName;
    private String password;
    private String serverAddress;

    // TCP Components
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;

    public LiveChatClient() {

        initHostName();
        runClient();// have fun
    }

    public void initHostName() {
        try {
            serverAddress = "<your system name>";
            if (serverAddress == null)
                System.exit(1);

            serverAddress = serverAddress.trim();
            if (serverAddress.length() == 0)// empty field
            {
                System.out.println("Server IP Address or Name can't be blank.");
                initHostName();
                return;
            }
            System.out.println("Trying to connect with server...\nServer IP Address:"
                    + serverAddress);

            // create socket
            InetAddress inetAddress = InetAddress.getByName(serverAddress);
            if (!inetAddress.isReachable(60000))// 60 sec
            {
                System.out
                        .println("Error! Unable to connect with server.\nServer IP Address may be wrong.");
                System.exit(1);
            }

            initPortNo();
        } catch (SocketException e) {
            System.out.println("Socket Exception:\n" + e);
            initHostName();
            return;
        } catch (IOException e) {
            initHostName();
            return;
        }
    }

    public void initPortNo() {
        try {

            String portNo = "1234";

            portNo = portNo.trim();
            if (portNo.length() == 0)// empty field
            {
                System.out.println("Server port No can't be blank.");
                initPortNo();
                return;
            }
            System.out.println("Trying to connect with server...\nServer Port No:" + portNo);

            socket = new Socket(serverAddress, 1234);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

        } catch (IOException e) {
            System.out.println("IO Exception:\n" + e);
            initPortNo();
            return;
        }
    }

    public void sendChatName() throws IOException {
        System.out.println("Enter user name:");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String name = br.readLine();
        if (name == null)
            System.exit(1);

        // title case (get only first 9 chars of chat name)
        chatName = name.trim();

        if (name.length() == 0) {
            System.out.println("Please enter user name.");
            sendChatName();
            return;
        }

        // sending opcode first then sending chatName to the server
        out.println(Opcode.CLIENT_USERNAME);
        out.println(chatName);
    }

    public void sendPassword() throws IOException {
        System.out.println("Enter password:");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String name = br.readLine();
        if (name == null)
            System.exit(1);

        // title case (get only first 9 chars of password)
        password = name.trim();

        if (name.length() == 0) {
            System.out.println("Please enter password.");
            sendPassword();
            return;
        }

        // sending opcode first then sending password to the server
        out.println(Opcode.CLIENT_PASSWORD);
        out.println(password);
    }

    public void runClient() {
        try {
            sendChatName();
            while (true) {
                int opcode = Integer.parseInt(in.readLine());
                switch (opcode) {
                    case Opcode.CLIENT_INVALID_USERNAME:
                        // this client is connecting
                        System.out.println(chatName + " is invalid user name. Try different one.");
                        sendChatName();

                        break;

                    case Opcode.CLIENT_PASSWORD:
                        sendPassword();

                        break;

                    case Opcode.CLIENT_INVALID_PASSWORD:
                        // this client is connecting
                        System.out.println(password + " is invalid password. Try different one.");
                        sendPassword();

                        break;

                    case Opcode.CLIENT_CONNECTED:
                        System.out.println(chatName + " is connected successfully.");

                        break;

                }
            }
        } catch (IOException e) {
            System.out.println("Client is closed...");
        }
    }

    // *********************************** Main Method ********************

    public static void main(String args[]) {
        new LiveChatClient();
    }

}

<强> ClientThread.java:

多个线程由服务器1为每个客户端启动,并包含有关所有已连接客户端的信息

/************************ Client Thread *******************/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientThread implements Runnable {
    // TCP Components
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    private String chatName;
    private String password;

    // seperate thread
    private Thread thread;

    // boolean variable to check that client is running or not
    private volatile boolean isRunning = true;

    // opcode
    private int opcode;
    private static Map<String, String> userpass = new HashMap<String, String>();

    static {
        userpass.put("amit", "pass");
        userpass.put("ajay", "word");
    }

    public ClientThread(Socket socket) {
        try {
            this.socket = socket;

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            thread = new Thread(this);
            thread.start();

        } catch (IOException e) {
            System.out.println(e);
        }
    }

    public void run() {
        try {
            while (isRunning) {
                if (!in.ready())
                    continue;

                opcode = Integer.parseInt(in.readLine());// getting opcode first from client
                switch (opcode) {
                    case Opcode.CLIENT_USERNAME:
                        chatName = in.readLine();

                        System.out.println(chatName + " is reqesting to connect.");
                        boolean result1 = userpass.containsKey(chatName);
                        if (result1) {
                            System.out.println(chatName + " is a valid username.");
                            out.println(Opcode.CLIENT_PASSWORD);
                        } else {
                            System.out.println(chatName + " is a invalid username.");
                            out.println(Opcode.CLIENT_INVALID_USERNAME);
                        }

                        break;

                    case Opcode.CLIENT_PASSWORD:
                        password = in.readLine();

                        System.out.println(chatName + " is reqesting to connect having password "
                                + password);
                        boolean result2 = userpass.get(chatName).equals(password);
                        if (result2) {
                            System.out.println(password + " is a valid password for username "
                                    + chatName);
                            out.println(Opcode.CLIENT_CONNECTED);
                        } else {
                            System.out.println(password + " is a invalid password for username "
                                    + chatName);
                            out.println(Opcode.CLIENT_INVALID_PASSWORD);
                        }

                        break;
                }
            }

            // close all connections
            out.close();
            in.close();
            socket.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

添加两个客户端时,这是输出

服务器:

ServerSocket[addr=computerName/14.98.241.102,port=0,localport=1234]
computerName:1234
abc is reqesting to connect.
abc is a invalid username.
ajay is reqesting to connect.
ajay is a valid username.
ajay is reqesting to connect having password word
word is a valid password for username ajay
amit is reqesting to connect.
amit is a valid username.
amit is reqesting to connect having password word
word is a invalid password for username amit
amit is reqesting to connect having password pass
pass is a valid password for username amit

客户端1:(阿贾伊)

Trying to connect with server...
Server IP Address:computerName
Trying to connect with server...
Server Port No:1234
Enter user name:
abc
abc is invalid user name. Try different one.
Enter user name:
ajay
Enter password:
word
ajay is connected successfully.

客户机2:(阿米特)

Trying to connect with server...
Server IP Address:computerName
Trying to connect with server...
Server Port No:1234
Enter user name:
amit
Enter password:
word
word is invalid password. Try different one.
Enter password:
pass
amit is connected successfully.

将此程序用作应用程序的初始启动程序。如果您想在程序中添加新功能,请与我们联系。

答案 1 :(得分:0)

可能你应该考虑学习JavaEE,你说的主要是做服务器的工作。每个客户端连接到服务器进行登录的位置。现在如果你需要在javaSE中使用100%桌面,你需要线程,每个线程将连接到本地登录。

JavaEE:http://www.roseindia.net/quickguide/tomcat/Logout.shtml

主题:http://www.vogella.com/tutorials/JavaConcurrency/article.html

我希望它有所帮助!!