如何引用位于不同文件夹/包中的服务器类

时间:2016-11-21 01:28:08

标签: java sockets client-server packages

我正在尝试实施多客户端服务器程序。我决定在不同的文件夹/包中实现每个客户端程序。同样,服务器程序将位于不同的包中。因此,当我在客户端创建套接字并需要引用服务器时,我该怎么做呢?如果服务器在另一台计算机上,我会提供IP地址。

Socket clientscoket = new Socket("server.java", 2100);

当服务器程序驻留在同一目录中时,此方法有效。如果服务器程序位于不同的目录中该怎么办?

编辑:

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

class ServerSide {
    static private HashMap<String, Socket> clientList = new HashMap<String, Socket>();

    public static void main(String argv[]) throws Exception {
        ServerSide ss = new ServerSide();
        new Listener(argv[0]);    
    }
}

class Listener implements Runnable {
    ServerSocket listenSocket;
    HashMap<String, Socket> hm = new HashMap<String, Socket>();

    Listener(String prt) throws NumberFormatException, IOException {
        String output;
        listenSocket = new ServerSocket(Integer.parseInt(prt));
        Thread t = new Thread(this);
        t.start();
    }

    public Listener() {
        // TODO Auto-generated constructor stub
    }

    // List<Socket> cList = new ArrayList<Socket>();
    // Create a new Thread. One for listening. Another for comms
    public void run() {
        boolean cont = true;
        while (cont) {
            Socket connectionSocket;
            try {
                connectionSocket = listenSocket.accept();
                new ClientThread(connectionSocket);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /*
         * BufferedReader inFromClient = new BufferedReader(new
         * InputStreamReader(connectionSocket.getInputStream()));
         * System.out.println("Input Stream created"); String cid =
         * inFromClient.readLine(); System.out.println(cid+" connected");
         * PrintWriter outToClient = new
         * PrintWriter(connectionSocket.getOutputStream());
         * outToClient.println("Hello "+cid); clientSentence =
         * inFromClient.readLine(); welcomeSocket.close(); cont = false;
         * 
         * System.out.println("Received: " + clientSentence);
         * capitalizedSentence = clientSentence.toUpperCase() + '\n';
         * outToClient.writeBytes(capitalizedSentence);
         */
    }

    public HashMap<String, Socket> getMap() {
        return hm;
    }
}

class ClientThread implements Runnable {
    String msg;
    Thread t;
    BufferedReader ipStream;
    boolean flag = true;
    Listener l = new Listener();

    ClientThread(Socket connectionSocket) throws IOException {
        System.out.println("We're here");
        t = new Thread(this);
        ipStream = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        if (ipStream.ready()) {
            String cid = ipStream.readLine();
            t.setName(cid);
            System.out.println(t.getName() + " connected");
            l.getMap().put(cid, connectionSocket);
            t.start();
        }
    }

    public void run() {
        try {
            while (flag) {
                if (ipStream.ready()) {
                    System.out.println("Stream ready");
                    msg = ipStream.readLine();
                    if (msg.equals("close")) {
                        System.out.println(t.getName() + " disconnected");
                        flag = false;
                        break;
                    } else {
                        String[] cmd = msg.split("\\s+");
                        System.out.println(msg);
                        if (cmd[0].equals("broadcast")) {
                            broadcast(cmd[1]);
                        } else if (cmd[0].equals("unicast")) {
                            unicast(cmd[1], cmd[2]);
                        } else if (cmd[0].equals("blockcast"))
                            blockcast(cmd[1], cmd[2]);
                        else
                            continue;

                    }
                }
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void broadcast(String msg) throws IOException {
        for (String k : l.getMap().keySet()) {
            if (k.equals(t.getName()))
                continue;
            Socket receiverSocket = new Socket(l.getMap().get(k).getInetAddress(), l.getMap().get(k).getPort());
            PrintWriter outToServer = new PrintWriter(receiverSocket.getOutputStream(), true);
            outToServer.println(msg);
        }
        System.out.println(msg);
    }

    public void unicast(String cID, String msg) {
        System.out.println(msg);
    }

    public void blockcast(String cID, String msg) {
        System.out.println(msg);
    }

}

2 个答案:

答案 0 :(得分:0)

  

所以,当我在客户端创建一个套接字并需要引用时   服务器,我该怎么办呢?如果服务器不同   电脑,我会提供IP地址吗?

无论如何,您需要提供IP地址,不能使用它的类名指定服务器。您始终必须指定主机地址。

  

Socket clientscoket = new Socket("server.java", 2100);

您在此处所做的是创建一个与Socket指定的主机绑定的server.java

如果您需要引用服务器,您应该尝试连接到服务器侦听的端口,而不是尝试使用类名来访问它...

如何实现它。

您可以将端口号分配给工厂类中的服务器类型,以便在需要时为您提供[Server]Socket

Class ConnectionFactory

private static final Map<String, Integer> ports = new HashMap<String, Integer>();

static {
    // These Servers would listen to these ports.
    ports.put("com.stackoverflow.multiconnect.servers.Server1", 5001);
    ports.put("com.stackoverflow.multiconnect.servers.Server2", 5502);
    ports.put("com.stackoverflow.multiconnect.servers.Server3", 8080);
}

您可以从此类返回服务器和客户端套接字的实例。

public static ServerSocket createServerSocket(Class<?> serverClass)
        throws IOException {
    return createServerSocket(serverClass.getName());
}

public static ServerSocket createServerSocket(String fqcn)
        throws IOException {
    Integer port = ports.get(fqcn);
    if (port == null)
        throw new IllegalArgumentException("No server registery found for " + fqcn);
    return new ServerSocket(port);
}

public static Socket createClientSocket(Class<?> serverClass)
        throws UnknownHostException, IOException {
    return createClientSocket(serverClass.getName());
}

public static Socket createClientSocket(String fqcn)
        throws UnknownHostException, IOException {
    Integer port = ports.get(fqcn);
    if (port == null)
        throw new IllegalArgumentException("No server registery found for " + fqcn);
    return new Socket("localhost", port);
}

现在,您可以:

//Open a server Socket
ServerSocket server1 = ConnectionFactory.createServerSocket(Server1.class);    

// Create a client to connect to a server
Socket client1 = ConnectionFactory.createClientSocket(Server1.class);

可以找到更详尽,更完整的例子here

答案 1 :(得分:-1)

尝试使用server.java

的目录的整个路径来代替server.java

所以home / user / class / server / server.java