Изменение реализации клиент-сервера с использованием Corba после запуска idlj -fall * .idl - PullRequest
0 голосов
/ 15 декабря 2018

Я установил свой IDL и запустил его, чтобы получить все мои заглушки, poa-файл и все, но я не совсем уверен, куда мне идти. Я запустил idlj -fall Server.idl, но моя программа не 'Пока не работает, и я не совсем понимаю, как какая-либо из функций Corba позволяет клиенту и серверу взаимодействовать друг с другом.

Idl-файл

/**
*
*/
module Java_Corba{
    interface Server{
        void newUser(in string name);
        void create(in string userInput, in string user);
        string list();
        string join1();
        string join2(in string input, in string user);
        string leave1(in string user);
        string leave2(in string input, in string user);
        string roomTime(in string input, in boolean increaseTime);
        string createDate(in long time);
        string writeMessage(in string msg, in string user);
    };
};  

И после его запуска я получил мои заглушки и serverpoa и все

package Java_Corba;


/**
* Java_Corba/_ServerStub.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from Server.idl
* Monday, November 26, 2018 1:52:12 o'clock AM CST
*/

public class _ServerStub extends org.omg.CORBA.portable.ObjectImpl implements Java_Corba.Server
{

  public void newUser (String name)
  {
            org.omg.CORBA.portable.InputStream $in = null;
            try {
                org.omg.CORBA.portable.OutputStream $out = _request ("newUser", true);
                $out.write_string (name);
                $in = _invoke ($out);
                return;
            } catch (org.omg.CORBA.portable.ApplicationException $ex) {
                $in = $ex.getInputStream ();
                String _id = $ex.getId ();
                throw new org.omg.CORBA.MARSHAL (_id);
            } catch (org.omg.CORBA.portable.RemarshalException $rm) {
                newUser (name        );
...
...
  private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException
  {
     String[] args = null;
     java.util.Properties props = null;
     org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);
   try {
     String str = orb.object_to_string (this);
     s.writeUTF (str);
   } finally {
     orb.destroy() ;
   }
  }
} // class _ServerStub

пакет Java_Corba;

/**
* Java_Corba/_ServerStub.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from Server.idl
* Monday, November 26, 2018 1:52:12 o'clock AM CST
*/

public class _ServerStub extends org.omg.CORBA.portable.ObjectImpl implements Java_Corba.Server
{

  public void newUser (String name)
  {
            org.omg.CORBA.portable.InputStream $in = null;
            try {
                org.omg.CORBA.portable.OutputStream $out = _request ("newUser", true);
                $out.write_string (name);
                $in = _invoke ($out);
                return;
            } catch (org.omg.CORBA.portable.ApplicationException $ex) {
                $in = $ex.getInputStream ();
                String _id = $ex.getId ();
                throw new org.omg.CORBA.MARSHAL (_id);
            } catch (org.omg.CORBA.portable.RemarshalException $rm) {
                newUser (name        );
            } finally {
                _releaseReply ($in);
            }
  } // newUser

  public void create (String userInput, String user)
...
...
  private void writeObject (java.io.ObjectOutputStream s) throws java.io.IOException
  {
     String[] args = null;
     java.util.Properties props = null;
     org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init (args, props);
   try {
     String str = orb.object_to_string (this);
     s.writeUTF (str);
   } finally {
     orb.destroy() ;
   }
  }
} // class _ServerStub

И у меня есть мой основной ServerImpl класс что все мои основные вещи находятся в

package Java_Corba;
//import server.Server;
//import server.ServerHelper;
//import server.ServerPOA;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.omg.CORBA.ORB;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

public class ServerImpl extends ServerPOA{

    private ORB orb;
    Server_helper server = new Server_helper();

    public void setORB(ORB orb) {
        this.orb = orb;
    }

    public void newUser(String name) {
            User user = new User(this.server, name);
    }

    public void create(String userInput, String user) {
        User u = server.getUser(user);
        u.create(userInput);
    }

    public String list() {
        String rooms = "";
        for (int j = 0; j < server.chatRooms.size(); j++) {
            rooms = rooms + server.chatRooms.get(j).getName() + "\n";
        }
        return rooms;
    }

    public String join1() {
        int end = server.chatRooms.size();
        if (end == 0) {
            return "There's currently no chat rooms";
        }else { 
            return "Which room?";
        }

    }

    public String join2(String input, String user) {
        int end = server.chatRooms.size();
        for (int k = 0; k < end; k++) {
            Chatroom room = server.chatRooms.get(k);
            if (room.getName().equals(input)) {
                User u = server.getUser(user);
                u.joinRoom(room);
                room.addUser(u);
                String message = "Chatroom " + input + " messages. \n";
                //Print the current messages in the chatroom to the user
                for (int j = 0; j < room.messages.size(); j++ ) {
                    message = message + room.messages.get(j) + "\n";
                }
                return message;
            } else if (k == end - 1) {
                return "There's no chat rooms by that name";
            }
        }
        return "There's no chat rooms by that name";
    }

    public String leave1(String user) {
        User u = server.getUser(user);
        int end = u.chatRoomLength();   //if the chatroom list of the user is empty
        if (end == 0) {
            return "You are not in any Chat Rooms";
        }else {
            return "Which room would you like to leave?";
        }
    }

    public String leave2(String input, String user) {
        int end = server.chatRooms.size();
        User u = server.getUser(user);
        for (int m = 0; m < end; m++) { //find the chatroom by the same name
            Chatroom room = server.chatRooms.get(m);
            if (room.getName().equals(input)) {
                u.chatRooms.remove(m);
                room.removeUser(u);
                return "Great! You've been removed from " + input;
            } else if (m == end - 1) {
                return "You're not in a chatroom named " + input;
            }
        }
        return "You're not in a chatroom named " + input;
    }

    public String roomTime(String input, boolean increaseTime) {
        int end = server.chatRooms.size();
        for (int k = 0; k < end; k++) {
            Chatroom room = server.chatRooms.get(k);
            if (room.getName().equals(input)) {
                String output = "Current time stamp on room: " + createDate(room.dateLastUsed);
                if (increaseTime == true) {
                    room.increaseTime();
                    output = output + "New time stamp on room: " + createDate(room.dateLastUsed);
                }
                return output;
            } else if (k == end - 1) {
                return "There's no chat rooms by that name";
            }
        }
        return "There's no chat rooms by that name";
    }

    public String createDate(long time) {
        Date date = new java.util.Date(time * 1000L);
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 
        // give a timezone reference for formatting (see comment at the bottom)
        sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4")); 
        String formattedDate = sdf.format(date);
        return formattedDate;
    }

    public String writeMessage(String msg, String user) {
        User u = server.getUser(user);
        int end = u.chatRoomLength();
        if (end == 0) {
            return "You can't write to any chat rooms because you are not in any";
        }
        for (int m = 0; m < end; m++) { //Add the users message to ALL the chatrooms the user is in
            Chatroom c = u.chatRooms.get(m);
            c.addMessage(msg);
            return "";
            //Send this added message to all the users in this chatroom

        }
        return "You can't write to any chat rooms because you are not in any";
    }

    public class ServerServer {
        public void main(String args[]) {
            try{
                // create and initialize the ORB
                ORB orb = ORB.init(args, null);

                // get reference to rootpoa & activate the POAManager
                POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
                rootpoa.the_POAManager().activate();

                // create servant and register it with the ORB
                ServerImpl serverImpl = new ServerImpl();

                //Ralph doesn't have a line like this, look into this
                serverImpl.setORB(orb);

                // get object reference from the servant
                org.omg.CORBA.Object ref = rootpoa.servant_to_reference(serverImpl);
                Server href = ServerHelper.narrow(ref);

                // get the root naming context
                // NameService invokes the name service
                org.omg.CORBA.Object objRef =
                        orb.resolve_initial_references("NameService");
                // Use NamingContextExt which is part of the Interoperable
                // Naming Service (INS) specification.
                NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

                // bind the Object Reference in Naming
                String name = "MyServer";
                NameComponent path[] = ncRef.to_name( name );
                ncRef.rebind(path, href);

                System.out.println("server.ServerServer ready and waiting ...");

                // wait for invocations from clients
                orb.run();
            }
            catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println("server.ConnServer Exiting ...");

        }
    }

    @Override
    public String createDate(int time) {
        // TODO Auto-generated method stub
        return null;
    }

    public static void main(String[] args) {
        ServerImpl si = new ServerImpl();
        ServerServer ss = si.new ServerServer();
        si.main(args);
    }

}

И мой клиентский класс

package Java_Corba;
import java.util.Scanner;
import java.io.IOException;
//import server.Server;
//import server.ServerHelper;
import org.omg.CORBA.ORB;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;

public class Client extends Thread{
    private String input;
    private String name;
    private String output;
    static ServerImpl serverImpl;
    Scanner reader = new Scanner(System.in);

    public Client() {
        try {
            reader = new Scanner(System.in);
            print("Enter a name");
            name = reader.nextLine();
            serverImpl.newUser(this.name);
            this.run();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String defaultMessage() {
        String message = "Create a chatroom: create \nList Chat Rooms: list \nJoin Chat Room: join \nLeave Chat Room: leave";
        return message;
    }

    private String create() {
        print("Name the Chatroom");
        String input = reader.nextLine();
        serverImpl.create(input, this.name);
        return "Joined room " + input;
    }

    private String joinr() {
        output = serverImpl.join1();
        if (output.charAt(0) == 'T') {
            return output;
        }else {
            print(output);
            input = reader.nextLine();
            output = serverImpl.join2(input, this.name);
            return output;
        }
    }

    private String leave() {
        output = serverImpl.leave1(this.name);
        if (input.charAt(0) == 'Y') {
            return output;
        }else {
            print(output);
            input = reader.nextLine();
            output = serverImpl.join2(input, this.name);
            return output;
        }
    }

    private String roomTime(boolean increaseTime) {
        output = serverImpl.join1();
        if (output.charAt(0) == 'T') {
            return output;
        }else {
            print(output);
            input = reader.nextLine();
            output = serverImpl.roomTime(input, increaseTime);
            return output;
        }
    }

    private String writeMessage(String msg) {
        return serverImpl.writeMessage(msg, this.name);
    }

    /*
     * Runs a thread for the client to constantly receive the clients input(non-Javadoc)
     * @see java.lang.Thread#run()
     */
    public void run() {
//      try {
            Scanner reader = new Scanner(System.in);
            String userInput;//Check if there is input from the user
            do {
                input = reader.nextLine();
                print(this.defaultMessage());
                //if the user has disconnected from the server, remove them from the list
                if (input.equals("create")){    //create a chat room
                    output = this.create();
                    print(output);
                }else if (input.equals("list")) {   //List the current chatrooms
                    output = serverImpl.list();
                    print(output);
                }else if (input.equals("join")) {   //Join the user to a chat room
                    output = this.joinr();
                    print(output);
                }else if (input.equals("leave")) {  //Remove the user from a chatroom
                    output = this.leave();
                    print(output);
                }else if (input.equals("x")) {
                    output = this.roomTime(true);
                    print(output);
                }else if (input.equals("time")) {
                    long time = System.currentTimeMillis() / 1000;
                    output = String.valueOf(serverImpl.createDate(time));
                    print(output);
                }else if (input.equals("roomTime")) {
                    output = this.roomTime(false);
                    print(output);
                }else if (input.equals("help")) {
                    print(this.defaultMessage());
                }else { //All other input is interpreted as a message to be posted in the chatrooms that the user is in
                    output = this.writeMessage(input);
                    print(output);
                }

            } while (input != null);
    }

    static void print(String x) {
        System.out.println(x);
    }

    public static void main(String args[]) {
        try{
            // create and initialize the ORB
            ORB orb = ORB.init(args, null);

            // get the root naming context
            org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");

            // Use NamingContextExt instead of NamingContext. This is
            // part of the Interoperable naming Service.
            NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

            // resolve the Object Reference in Naming
            String name = "Server";
            serverImpl = (ServerImpl) ServerHelper.narrow(ncRef.resolve_str(name));

            System.out.println("Obtained a handle on server object: " + serverImpl);
            Client client = new Client();
            client.run();

            //new Thread(new Input()).start();
            //new Thread(new Output()).start();

        } catch (Exception e) {
            System.out.println("ERROR : " + e) ;
            e.printStackTrace(System.out);
        }
    }


}
...