running a client/server prog on a single system

前端 未结 4 957
一生所求
一生所求 2021-01-24 22:58

im wondering if there are two programs, one called server and the other called client and these two are illustrating a server and client respectively,

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-24 23:45

    Yes, you can write such a program. There is a useful tutorial for this. In short, it all boils down to prepare a ServerSocket:

    ServerSocket createSocket() {
        ServerSocket serverSocket;
        try {
            serverSocket = new ServerSocket(3000);
        } catch (IOException ex) {
            ex.printStackTrace(System.err);
            throw ex;
        }
        return serverSocket;
    }
    

    From the programmer's point of view, there is no difference between a server residing on a remote machine or on a local one.

    You could try writing two different programs, one for the server and one for the client. This is the main for the client:

    public static void main(String[] args) {
      try {
          TCPClient client = new TCPClient() {};
          client.run();
      } catch(IOException e) {
        System.err.println("Error in Client " + e.getMessage());
      }
    

    And this for the server:

    public static void main(String[] args) {
      try {
          TCPServer server = new TCPServer() {};
          server.run();
      } catch(IOException e) {
        System.err.println("Error in Server " + e.getMessage());
      }
    

    Then run the server first and then the client in a different console.

提交回复
热议问题