使用一台服务器处理多个客户端?

时间:2016-05-02 19:45:32

标签: java network-programming

我需要对我的代码做些什么才能让多个客户端连接到服务器呢?请解释一下因为我对网络编程很新。

ServerMethod.java

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class serverMethod {
    public void lookForConnection() {
        Socket connection;
        {
            try {
                System.out.print("Program running...");
                ServerSocket serverSocket = new ServerSocket(6789);
                while (true) {
                    connection = serverSocket.accept();
                    if (connection != null) {
                        System.out.print("Connected Succesfully!");
                        System.out.print(connection.getInetAddress().getHostName());
                    }
                }
            } catch (IOException ex) {
                System.out.println(ex.toString());
            }
        }
    }
}

//执行服务器的类

public class Server {
    public static void main(String[] args) {
        serverMethod Server = new serverMethod();
        Server.lookForConnection();
    }
}

客户端方法

import java.io.EOFException;
import java.util.Scanner;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class clientMethod {

    public String serverIP;
    public String password;
    public Socket connection;

    public void Client(String host) {
        serverIP = host;
    }

    public void startRunning() {
        try {
            Scanner console = new Scanner(System.in);
            System.out.println("Attempting connection...");
            System.out.print("Please provide the admin password: ");
            password = console.next();
            if (password.compareTo("root") == 0) {
                connectToServer();
            }

        } catch (EOFException eofException) {
            System.out.print("\n Client terminated the connection");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    private void connectToServer() throws IOException {
        System.out.println("Attempting connection...");
        connection = new Socket(InetAddress.getByName(serverIP), 6789);
        System.out.println("Connected to " + connection.getInetAddress().getHostName());
    }
}

启动客户端的类

import java.io.IOException;

public class Client {
    public static void main(String[] args) throws IOException {
        clientMethod client = new clientMethod();
        client.Client("192.1xx.x3.x7"); //for posting purposes, replaced the ip
        client.startRunning();
    }
}

0 个答案:

没有答案