Client/Server Class

Hi,
I am new to Java Programming and I have a question.
I am trying to create a server class that includes the method randomColor and the method drawCircle. The driver/client class needs to draw a circle by calling the methods of a server object. I don't want to call drawOval() method directly in the driver/client class.
The result is basically a random circle with a random color.
Thanks for all your help.

Could you be a little more specific as to what you mean by client server? Do you want to run a client on one computer and the server on another? In that case, it would easier to create a Socket connection and send a specific byte or byte sequence to the server telling it to draw a circle.

Similar Messages

  • Client/Server hang up?

    I'm writing a basic client server program. I created an ArrayList to hold all the sockets of a connection so each client could, hopefully, eventually interact.
    Right now my client is a text field with a text area under it. A user types a command up top and then hits enter and sends that along to the server. However when i send in the message it seems to hang up and never sends back a reply. But what's really odd about it, is that if i close my server window and there by shutting it down the client then outputs exactly what i expected it to if it was working right. So im curious why there's this hangup in my code?
    Server:
    import java.awt.BorderLayout;
    import java.awt.Font;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class Server extends JFrame{
              private JTextArea jta = new JTextArea();
              private static ArrayList<Socket> clients = new ArrayList<Socket>();
              public Server(){
                   getContentPane().setLayout(new BorderLayout());
                   getContentPane().add(new JScrollPane(jta), BorderLayout.CENTER);
                   jta.setFont( new Font( "Times", Font.BOLD, 20));
                   setSize(500, 300);
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   setVisible(true);
                   try{
                        setTitle("Server: " + InetAddress.getLocalHost().getHostName());
                        int clientNo = 1;
                        ServerSocket serverSocket = new ServerSocket(0);
                        jta.append("Port: " + serverSocket.getLocalPort() + "\n");
                        while(true){
                             Socket socket = serverSocket.accept();
                             InetAddress inetAddress = socket.getInetAddress();
                             clients.add(socket);
                             World thread = new World(socket);
                             jta.append("Connected with client :" + clientNo + "\n");
                             thread.start();
                             clientNo++;
                   }catch(IOException ex){
                        System.err.println(ex);
              public static void main(String[] args){
                   new Server();
              public static ArrayList getClients(){
                   return clients;
         }World:
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.Scanner;
    public class World extends Thread {
         private Socket mySocket;
         private int myPort;
         private InetAddress myInetAddress;
         private String myHostName;
         private ArrayList<Socket> theClients;
         public World(Socket newSocket) {
              mySocket = newSocket;
              myPort = mySocket.getPort();
              myInetAddress = mySocket.getInetAddress();
              myHostName = myInetAddress.getHostName();
         public void run() {
              String test;
              Scanner input = null;
              PrintWriter output = null;
              try {
                   String fileName;
                   input = new Scanner(mySocket.getInputStream());
                   output = new PrintWriter(mySocket.getOutputStream(), true);
              }catch(IOException e){
              output.println("Please Enter Command");
              while((test = input.nextLine()) != null){
                   if(test.contains("get clients") ){
                        theClients = Server.getClients();
                        for(int i = 0; i < theClients.size(); i++){
                             output.println(theClients.get(i).getInetAddress().getHostName());
                        output.flush();
                   }else{
                        output.println("not sure");
                        output.flush();
    }Client:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.Scanner;
    import javax.swing.*;
    public class Client extends JFrame implements ActionListener{
         private JTextField jtf;
         private JTextArea jta = new JTextArea();
         private PrintWriter output;
         private Scanner input;
         public Client(String host, int port){
              JPanel p1 = new JPanel();
              p1.setLayout(new BorderLayout());
              p1.add(jtf = new JTextField(10), BorderLayout.CENTER);
              jtf.setHorizontalAlignment(JTextField.RIGHT);
              jtf.setFont(new Font("Times", Font.BOLD, 20));
              jta.setFont(new Font("Times", Font.BOLD, 20));
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(p1, BorderLayout.NORTH);
              getContentPane().add(new JScrollPane(jta), BorderLayout.CENTER);
              jtf.addActionListener(this);
              setSize(500,300);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
              try{
                   setTitle("Client: " + InetAddress.getLocalHost().getHostName());
                   Socket socket = new Socket(host, port);
                   input = new Scanner(socket.getInputStream());
                   output = new PrintWriter(socket.getOutputStream(), true);
                   jta.append(input.nextLine() + "\n");
              }catch(IOException ex){
                   jta.append(ex.toString() + "\n");
         public void actionPerformed(ActionEvent e){
              String nextLine;
              String findFile = jtf.getText().trim();
              ((JTextField)(e.getSource())).setEditable(false);
              if ( e.getSource() instanceof JTextField){
                        jta.append("Getting file: \"" + findFile + "\" \n");
                        output.println(findFile);
                        output.flush();
                        while(input.hasNext()){
                             nextLine = input.nextLine();
                             jta.append(nextLine + "\n");
         public static void main(String[] args){
              int portSend;
              if (args.length != 2){
                   System.out.println("not Enough arguments");
                   System.exit(-1);
              portSend = Integer.parseInt(args[1]);
              new Client(args[0], portSend);
    }

    Don't run networking code in the constructor. Start a separate thread for the accept loop.

  • Best practice for client-server(Socket) application

    I want to build a client-server application
    1) On startup.. client creates connection to Server and keeps reading data from server
    2) Server keeps on sending different messages
    3) Based on messages(Async) from server client view has to be changed
    I tried different cases ended up facing IllegalStateChangeException while updating GUI
    So what is the best way to do this?
    Please give a working example .
    Thanks,
    Vijay
    Edited by: 844427 on Jan 12, 2012 12:15 AM
    Edited by: 844427 on Jan 12, 2012 12:16 AM

    Hi EJP,
    Thanks for the suggestion ,
    Here is sample code :
    public class Lobby implements LobbyModelsChangeListener{
        Stage stage;
        ListView<String> listView;
        ObservableList ol;
         public Lobby(Stage primaryStage) {
            stage = primaryStage;
               ProxyServer.startReadFromServer();//Connects to Socket Server
             ProxyServer.addLobbyModelChangeListener(this);//So that any data from server is fetched to Lobby
            init();
        private void init() {
              ProxyServer.getLobbyList();//Send
            ol = FXCollections.observableArrayList(
              "Loading Data..."
            ol.addListener(new ListChangeListener(){
                @Override
                public void onChanged(Change change) {
                    listView.setItems(ol);
         Group root = new Group();
        stage.setScene(new Scene(root));
         listView = new ListView<String>();
        listView.maxWidth(stage.getWidth());
         listView.setItems(ol);
         listView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        istView.setOnMouseClicked(new EventHandler<MouseEvent>(){
                @Override
                public void handle(MouseEvent t) {
    //                ListView lv = (ListView) t.getSource();
                    new NewPage(stage);
         root.getChildren().add(listView);
         @Override
        public void updateLobby(LobbyListModel[] changes) {
    //        listView.getItems().clear();
            String[] ar = new String[changes.length];
            for(int i=0;i<changes.length;i++)
                if(changes!=null)
    System.out.println(changes[i].getName());
    ar[i] = changes[i].getName();
    ol.addAll(ar);
    ProxyServer.javaProxyServer
    //Implements runnable
    public void run()
         ......//code to read data from server
    //make array of LobbyListModel[] ltm based on data from server
         fireLobbyModelChangeEvent(ltm);
    void addLobbyModelChangeListener(LobbyModelsChangeListener aThis) {
    this.lobbyModelsChangeListener = aThis;
         private void fireLobbyModelChangeEvent(LobbyListModel[] changes) {
    LobbyModelsChangeListener listner
    = (LobbyModelsChangeListener) lobbyModelsChangeListener;
    listner.updateLobby(changes);
    Exception :
    java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-5
             at line         ol.addAll(ar);
    But ListView is getting updated with new data...so not sure if its right way to proceed...
    Thanks,
    Vijay                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Client/server

    Hi, i am doing a client/server arc .I have a server , that will connected to the oracle , using jdbc.The client here is an application, how do i change it to applet?
    The server code
    import java.sql.*;
    import java.util.Properties;
    import java.io.*;
    import java.net.*;
    public class CommentsServer extends Thread {
    public static final int DEFAULT_PORT = 7777;
    protected int port;
    protected ServerSocket server;
    String username ="combtest";
    String password = "combtest";
    public static void main (String args[]) {
    int port=0;
    if (args.length == 1) {
    try {
    port = Integer.parseInt (args[0]);
    } catch (NumberFormatException e) { }
    try {
         Class.forName("oracle.jdbc.driver.OracleDriver");
    String sourceURL ="jdbc:oracle:thin:@klm:1521:KLMPMIS";
    String user="combtest";
    String password="combtest";
    catch (Exception e) {
    System.err.println("Failed to load JDBC driver.");
    System.exit (1);
    new CommentsServer (port);
    public CommentsServer (int port) {
    super ("Comments Server");
    if (port == 0)
    port = DEFAULT_PORT;
    this.port = port;
    try {
    server = new ServerSocket (port);
    } catch (IOException e) {
    System.err.println ("Error creating server");
    System.exit (1);
    start();
    public void run() {
    System.out.println ("Server Running");
    ThreadGroup connections = new ThreadGroup ("Comment Connections");
    connections.setMaxPriority(this.getPriority()-1);
    try {
    while (true) {
    Socket client = server.accept();
    System.out.println ("Connection from: " + client.getInetAddress().getHostName());
    CommentsConnection c = new CommentsConnection (connections, client);
    } catch (IOException e) {
    System.err.println ("Exception listening");
    System.exit (1);
    System.exit (0);
    class CommentsConnection extends Thread {
    static int counter = 0;
    protected ObjectInputStream in;
    protected PrintWriter out;
    public CommentsConnection (ThreadGroup group, Socket client) {
    super (group, "Connection " + counter++);
    try {
    in = new ObjectInputStream (client.getInputStream ());
    out = new PrintWriter (client.getOutputStream(), true);
    } catch (IOException e) {
    try {
    client.close();
    } catch (IOException e2) { }
    System.err.println ("Unable to connect.");
    return;
    start();
    public void run () {
    try {
    String mode = (String)in.readObject();
    if (mode.equals("insert")) {
         String name=(String)in.readObject();
    try {
         String u="jdbc:oracle:thin:@klm:1521:KLMPMIS";
         Connection con=DriverManager.getConnection(u,"combtest","combtest");
         PreparedStatement prep=con.prepareStatement("Insert into TEST values(?)");
         prep.setString(1,name);
         if(prep.executeUpdate()!=1)
         throw new Exception("Bad update");
    } catch (Exception e) {
    out.println ("Error updating: " + e);
    return;
    } else if (mode.equals("query")) {
    try {
         Connection con=DriverManager.getConnection("jdbc:oracle:thin:@klmsph1:1521:KLMPMIS","combtest","combtest");
    Statement statement=con.createStatement();
    ResultSet result=statement.executeQuery("SELECT * FROM TEST");
    out.println("Name");
    int nameCol=result.findColumn("NAME");
    String name,user,comments;
    while(result.next())
         name=result.getString(nameCol);
         out.println(name);
    statement.close();
    con.close();
    } catch (Exception e) {
    out.println ("Error querying: " + e);
    return;
    } else {
    out.println ("Invalid Command: " + mode);
    } catch (Exception e) {
    out.println ("Error reading Stream: " + e);
    out.close();
    the client code
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CommentsClient extends JApplet{
    TextArea ta;
    TextField name;     
    public static final int DEFAULT_PORT = 7777;
    private static final String QueryString = "query";
    private static final String InsertString = "insert";
    private int port = 0;
    private String host = null;
    private OutputStream os = null;
    public CommentsClient (String host, int port, OutputStream os) {
    this.host = host;
    this.port = ((port == 0) ? DEFAULT_PORT : port);
    this.os = os;
    query();
    public CommentsClient (String host, int port, OutputStream os,
    String name) {
    this.host = host;
    this.port = ((port == 0) ? DEFAULT_PORT : port);
    this.os = os;
    insert(name);
    private void query () {
    PrintWriter out = new PrintWriter (os, true);
    try {
    Socket s = new Socket (host, port);
    ObjectOutputStream oos = new ObjectOutputStream (s.getOutputStream());
    // PrintWriter out=new PrintWriter(s.getOutputStream(),true);
    oos.writeObject (QueryString);
    oos.flush();
    BufferedReader in = new BufferedReader (new InputStreamReader (s.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
    out.println (line);
    out.close();
    s.close();
    } catch (IOException e) {
    out.println ("Error querying." + e);
    return;
    private void insert (String name) {
    PrintWriter out = new PrintWriter (os, true);
    try {
    Socket s = new Socket (host, port);
    ObjectOutputStream oos = new ObjectOutputStream (s.getOutputStream());
    oos.writeObject (InsertString);
    oos.writeObject (name);
    oos.flush();
    BufferedReader in = new BufferedReader (new InputStreamReader (s.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
    out.println (line);
    oos.close();
    s.close();
    } catch (IOException e) {
    out.println ("Error inserting." + e);
    return;
    public static void main (String args[]) {
    if (args.length == 0) {
    CommentsClient cc = new CommentsClient ("localhost", 0, System.out);
    } else if (args.length == 1) {
    CommentsClient cc = new CommentsClient ("localhost", 0, System.out, args[0]);
    the applet (acts as an interface)
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.io.*;
    //<applet code = "CommentsApplet" width = 800 height = 600>
    //</applet>
    public class CommentsApplet extends Applet {
    TextArea ta;
    TextField name;
    TextField user;
    TextField comments;
    public void init () {
    Panel p1 = new Panel(new BorderLayout(10, 10));
    Button b1 = new Button ("Query");
    p1.add (b1, BorderLayout.SOUTH);
    ta = new TextArea ();
    ta.setEditable(false);
    p1.add (ta, BorderLayout.CENTER);
    b1.addActionListener (new ActionListener() {
    public void actionPerformed (ActionEvent e) {
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    CommentsClient cc = new CommentsClient ("localhost", 0, bao);
    ta.setText (bao.toString());
    add (p1);
    Panel p2 = new Panel (new BorderLayout (10, 10));
    Button b2 = new Button ("Insert");
    p2.add (b2, BorderLayout.SOUTH);
    Panel p3 = new Panel();
    name = new TextField ("", 10);
    p3.add (name);
    p2.add (p3, BorderLayout.CENTER);
    b2.addActionListener (new ActionListener() {
    public void actionPerformed (ActionEvent e) {
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    CommentsClient cc = new CommentsClient ("localhost", 0, bao, name.getText());
    ta.setText (bao.toString());
    add (p2);
    the html file
    <html>
    <body>
    <hr>
    <applet
    code=CommentsApplet.class
    width = 400
    height = 400
    >
    </applet>
    <hr>
    </body>
    </html>
    Thanks in advance,
    Jessy

    hi
    I have no idea what you are doing. Strange programming
    public class CommentsClient extends JApplet why does it extends JApplet when it isn't a JApplet but an application
    and why is there a second applet
    public class CommentsApplet extends Applet (should this be extends JPanel??)
    but for normal classes this is the procedure
    rename the constructor in "public void init()" the method init is automaticly called by the browser.
    remove the main method if there is some code in the main method that needed move it to the init method. ( in your case the arguments can't be read from the command line but must be read out of the *.html file )

  • OLE Alternatives in Forms 6i Client Server

    I'm fishing for some advice and maybe some examples of how to get around an OLE issue that's adversely affecting an upgrade project.
    We're currently migrating a Forms 4.5 application to 6i. This application displays MS Word documents (OLE Container) that are stored in the database and uses OLE to open manipulate, and save the documents back to the database. We've come across some serious problems with OLE and 6i that don't look like they'll be fixed any time soon (bug #2615804 in particular).
    Since OLE (ActiveX) is not supported a web delivered configuration, we're looking at an alternative to interacting and storing Word documents using a client/server configuration. This will have the added bonus of making the move to web delivery once we decide to go down that path.
    Has anyone out there had any good experience with overcoming this OLE problem? It seems like every pre-Forms 9i book out there has touted OLE as a way of interacting with Office tools and now OLE has become a roadblock.
    I've had a look at the JACOB example, but that doesn't really help if you're not deploying via the web.

    With the beans you've looking at visual stuff : like the look and feel project
    With the importer it's more like leveraging java functionality : in my case I've just implemented a call to a webservice on an application server. There is nothing visual here and it's just called via a straight bit of PL/SQL that call my java classes ( however, in that case I could also use UTL_HTTP directly to make the call and thus not bother with java importer - but the database wouldn't allow UTL_HTTP calls :( )
    For both of these you'd need to tell forms where to find the JAR file in it's java environment - but you won't have that in c/s
    Another way is to load up java code into the database and process it within the database and hide it completely from Forms. I've done this sort of thing loading Apache-FOP into Oracle and creating PDF files in the database (as BLOBS) from XML/XSL also in the database as XMLTYPES.
    At least that's my view on how it fits together ... maybe others know more :)
    Steve

  • JMX Client/Server Classpath error

    Good morning,
    I have some aplication thats monitoring Websphere MQ queues.
    For this i'm use some MQ Jars, but its work fine.
    I have JMX Client/Server, for connect into MQ Server, my aplication use the MQ class MQConstants.
    My JMX connection work fine to. So, my problem is.
    When I try to invoke my aplication method
    mbsc.invoke(objectName, "execute", params, sig);
    ....the fallow errors appears
    javax.management.RuntimeErrorException: Error thrown in operation execute
         at com.sun.jmx.mbeanserver.StandardMetaDataImpl.invoke(Unknown Source)
         at com.sun.jmx.mbeanserver.MetaDataImpl.invoke(Unknown Source)
         at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(Unknown Source)
         at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(Unknown Source)
         at javax.management.remote.rmi.RMIConnectionImpl.doOperation(Unknown Source)
         at javax.management.remote.rmi.RMIConnectionImpl.access$100(Unknown Source)
         at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(Unknown Source)
         at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(Unknown Source)
         at javax.management.remote.rmi.RMIConnectionImpl.invoke(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
         at sun.rmi.transport.Transport$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.rmi.transport.Transport.serviceCall(Unknown Source)
         at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
         at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
         at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:247)
         at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:223)
         at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:126)
         at com.sun.jmx.remote.internal.PRef.invoke(Unknown Source)
         at javax.management.remote.rmi.RMIConnectionImpl_Stub.invoke(Unknown Source)
         at javax.management.remote.rmi.RMIConnector$RemoteMBeanServerConnection.invoke(RMIConnector.java:972)
         at br.com.flexvision.mq.FlexJMXClient.connectMBClient(FlexJMXClient.java:67)
         at br.com.flexvision.mq.FlexJMXClient.main(FlexJMXClient.java:101)
    Caused by: java.lang.NoClassDefFoundError: com/ibm/mq/constants/MQConstants
         at br.com.flexvision.mq.beans.FlexMQStatistics.processFieldsTypes(FlexMQStatistics.java:209)
         at br.com.flexvision.mq.beans.FlexMQStatistics.execute(FlexMQStatistics.java:30)
         at br.com.flexvision.mq.beans.FlexMQStatistics.execute(FlexMQStatistics.java:25)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at com.sun.jmx.mbeanserver.StandardMetaDataImpl.invoke(Unknown Source)
         at com.sun.jmx.mbeanserver.MetaDataImpl.invoke(Unknown Source)
         at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(Unknown Source)
         at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(Unknown Source)
         at javax.management.remote.rmi.RMIConnectionImpl.doOperation(Unknown Source)
         at javax.management.remote.rmi.RMIConnectionImpl.access$100(Unknown Source)
         at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(Unknown Source)
         at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(Unknown Source)
         at javax.management.remote.rmi.RMIConnectionImpl.invoke(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
         at sun.rmi.transport.Transport$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.rmi.transport.Transport.serviceCall(Unknown Source)
         at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
         at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)The most important line in this error is:
    Caused by: java.lang.NoClassDefFoundError: com/ibm/mq/constants/MQConstants
    Because this is de MQ jar that i need.
    I try to set this into server class path, but doesn't work.
    Somebody knows how i fix this?

    And your server has this FileObject class on its classpath, does it?

  • Applet socket problem in client-server, urgent!

    Dear All:
    I have implemented a client server teamwork environment. I have managered to get the server running fine. The server is responsible for passing messages between clients and accessing Oracle database using JDBC. The client is a Java Applet. The code is like the following. The problem is when I try to register the client, the socket connection get java.security.AccessControlException: access denied(java.net.SocketPermission mugca.its.monash.edu.
    au resolve)
    However, I have written a Java application with the same socket connection method to connect to the same server, it connects to the server without any problem. Is it because of the applet security problem? How should I solve it? Very appreciate for any ideas.
    public class User extends java.applet.Applet implements ActionListener, ItemListener
    public void init()
    Authentication auth = new Authentication((Frame)anchorpoint);
    if(auth.getConnectionStreams() != null) {
    ConnectionStreams server_conn = auth.getConnectionStreams();
    // Authenticates the user and establishes a connection to the server
    class Authentication extends Dialog implements ActionListener, KeyListener {
    // Object holding information relevant to the server connection
    ConnectionStreams server_conn;
    final static int port = 6012;
    // Authenticates the user and establishes connection to the server
    public Authentication(Frame parent) {
    // call the class Dialog's constructor
    super(parent, "User Authentication", true);
    setLocation(parent.getSize().width/3, parent.getSize().height/2);
    setupDialog();
    // sets up the components of the dialog box
    private void setupDialog() {
    // create and set the layout manager
    //Create a username text field here
    //Create a password text field here
    //Create a OK button here
    public void actionPerformed(ActionEvent e) {
    authenticateUser();
    dispose();
    // returns the ConnectionStreams object
    public ConnectionStreams getConnectionStreams() {
    return(server_conn);
    // authenticates the user
    private void authenticateUser() {
    Socket socket;
    InetAddress address;
    try {
    // open socket to server
    System.out.println("Ready to connect to server on: " + port);
    socket = new Socket("mugca.its.monash.edu.au", port);
    address = socket.getInetAddress();
    System.out.println("The hostname,address,hostaddress,localhost is:" + address.getHostName() + ";\n" +
    address.getAddress() + ";\n" +
    address.getHostAddress() + ";\n" +
    address.getLocalHost());
    catch(Exception e) {
    displayMessage("Error occured. See console");
    System.err.println(e);
                                  e.printStackTrace();
    }

    Hi, there:
    Thanks for the help. But I don't have to configure the security policy. Instead, inspired by a message in this forum, I simply upload the applet to the HTTP server (mugca.its.monash.edu.au) where my won server is running. Then the applet is download from the server and running fine in my local machine.
    Dengsheng

  • Oracle form 6i in client server mode to call web service

    Hi,
    I am using oracle form 6i running in client server mode. My database version is 8.1.7.4. Now I am required to call an external web service. Is it possible to call web service without the existence of application server or web server? Please help!

    I have tried the method illustrated by the Form 10g Demo. However, when I select the Import Java Classes from the pull down menu, I have got the following error:
    PDE-UJI002 Unable to find the required Java Importer Classes.
    My Oracle Form version is as follows:
    Forms [32 Bit] Version 6.0.8.19.2 (Production)
    Oracle8i Enterprise Edition Release 8.1.7.0.0 - 64bit Production
    With the Partitioning option
    JServer Release 8.1.7.0.0 - 64bit Production
    Oracle Toolkit Version 6.0.8.19.1 (Production)
    PL/SQL Version 8.0.6.3.0 (Production)
    Oracle Procedure Builder V6.0.8.17.0 Build #863 - Production
    PL/SQL Editor (c) WinMain Software (www.winmain.com), v1.0 (Production)
    Oracle Query Builder 6.0.7.1.0 - Production
    Oracle Virtual Graphics System Version 6.0.5.38.0 (Production)
    Oracle Tools GUI Utilities Version 6.0.8.11.0 (Production)
    Oracle Multimedia Version 6.0.8.18.1 (Production)
    Oracle Tools Integration Version 6.0.8.18.0 (Production)
    Oracle Tools Common Area Version 6.0.8.18.0
    Oracle CORE Version 4.0.6.0.0 - Production
    Please help !

  • Incorrect decryption operation in client-server

    Hi all, sorry for my English, I don't know where is the problem and I don't see examples for internet.
    I have a cliente-server aplication, where client read a file, encrypt it and send it to server. The server doesn't decrypt de text correcty. For example if the file contents:
    "Hola, probando el cifrado y descifrado.", the server shows "Hola, probando eifrado."
    I think that the problem is in the form for send and receive the cipher text.
    I put the code for client:
    import java.net.*;
    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
    class ClientAES {
      public static void main(String argv[]) {
        try {
          System.out.print("Introduce the key : ");
          String cadena = Teclado.readString();
          SecureRandom rand = new SecureRandom(cadena.getBytes());
          System.out.println("Generating key...");
          KeyGenerator keyGen = KeyGenerator.getInstance("AES");
          keyGen.init(rand);
          SecretKey desKey = keyGen.generateKey();
          System.out.println("Key generated");
          Socket s=new Socket(argv[0],4096);
          FileInputStream fis = new FileInputStream(argv[1]);
          byte[] b=new byte[fis.available()];
          System.out.println("Bytes that can be read of file: "+fis.available());
          fis.read(b);
          System.out.println(Text send: "+new String(b));
          Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
          cipher.init(cipher.ENCRYPT_MODE,desKey);
          CipherOutputStream cos = new CipherOutputStream(s.getOutputStream(), cipher);
          cos.write(b, 0, b.length);
          fis.close();
          cos.close();
          s.close();
        } catch (Exception e) { e.printStackTrace(); }
    }and server:
    import java.net.*;
    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
    class ServerAES {
      public static void main(String argv[]) {
        try {
          System.out.print("Introduce the key: ");
          String cadena = Teclado.readString();
          SecureRandom rand = new SecureRandom(cadena.getBytes());
          System.out.println("Generating key...");
          KeyGenerator keyGen = KeyGenerator.getInstance("AES");
          keyGen.init(rand);
          SecretKey desKey = keyGen.generateKey();
          System.out.println("Key generated");
          ServerSocket servidor=new ServerSocket(4096);
          System.out.println("Waiting a client...");
          Socket s=servidor.accept();
          System.out.println("Recieve a client connection");
          Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
          cipher.init(cipher.DECRYPT_MODE,desKey);
          CipherInputStream cis = new CipherInputStream(s.getInputStream(), cipher);
          byte[] in = new byte[cipher.getBlockSize()];
          int length;   
          System.out.println(cipher.getBlockSize());
           length = cis.read(in,  0, in.length);
          System.out.println(new String(in)+new String(cipher.doFinal()));
          cis.close();
          s.close();
        } catch (Exception e) { e.printStackTrace(); }
    }

    eeeh, if I understand your code correctly, then you are creating keys in each process. That means, you'll have two different keys. But you are using AES, which is a symmetric encryption algorithm. Hence you'll need to have the same key on both sides. Otherwise you'll not decrypting the stuff you where encrypting before.
    stephan

  • ActiveX Bridge Usage in Client-Server architecture

    Hi,
    We developed an application (client-server architecture) based on RMI layer. Now we want to expose client as an ActiveX Control. Assume, server is running on one m/c, client is running on different m/c. Now in other m/c, on VB container my client activex is running. This activex should fetch data from server(through java based client) and should display it.
    We implemented an activex control for client, it is interacting with server. To show server data it should use one user-defined object class. We made this object as public static. But we are not able to use this object on activex side. Even serializing this object and reading it again is also not working.
    If anyone has idea on debugging this issue, please help us.
    Sagar.

    Use the 'NI AlarmEvent Browser' ActiveX control.   Set the machine as the remote station.  Lots of parameters.
    Mike
    Mike Crabtree - Lead Developer
    Destek of Nevada, Inc. / Digital Telemetry Systems, Inc.
    (866) 964-6948 / (760) 247-9512

  • Seperate instances of server class for authentication

    I'd like to implement some form of authentication in my server class. I thought about adding a few login routines and while the client hasn't authenticated itself all calls to functions other than the login stuff will throw Exceptions.
    However, as I understand from the (in my opinion chaotic documentation and tutorial) every UnicastRemoteObject class is instanced only once and after that every client will use a threaded version of that same class instance... This would mean that if one client logs in, all clients log in as the object doesn't distinguise between clients.
    So I either need a way to instance the server class for every client or (perhaps even more graceful) use a Login class that spawns a server class as soon as the login has been accepted.
    Unfortunately I can't find anything on the web or the forums about this (lotsa problems like mine but either unanswered or different enough to be less than helpful).

    I'd like to implement some form of authentication in
    my server class. I thought about adding a few login
    routines and while the client hasn't authenticated
    itself all calls to functions other than the login
    stuff will throw Exceptions.
    However, as I understand from the (in my opinion
    chaotic documentation and tutorial) every
    UnicastRemoteObject class is instanced only once and
    after that every client will use a threaded version
    of that same class instance.No, you can have as many instances as you like but you have to start with a single object which is bound into the Registry. What you are after is a Session pattern like this:
    public interface Login extends Remote
      Session login(String credentials) throws RemoteException;
    public interface Session extends Remote
    /// ... whatever you want
    then a singleton instance of LoginImpl is bound to the registry, the client retrieves it, tries to get a Session by logging in. The implementation of login() just looks like this:
    public Session login(String credentials) throws RemoteException
    // check credentials, RemoteServer.getClientHost() &c:
    if not acceptable throw new AccessException();
    // otherwise
    return new SessionImpl(credientials);
    }Easy as pie.

  • File transfer, read write through sockets in client server programming java

    Hello All, need help again.
    I am trying to create a Client server program, where, the Client first sends a file to Server, on accepting the file, the server generates another file(probably xml), send it to the client as a response, the client read the response xml, parse it and display some data. now I am successful sending the file to the server, but could not figure out how the server can create and send a xml file and send it to the client as response, please help. below are my codes for client and server
    Client side
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class XMLSocketC
         public static void main(String[] args) throws IOException
              //Establish a connection to socket
              Socket toServer = null;
              String host = "127.0.0.1";     
              int port = 4444;
              try
                   toServer = new Socket(host, port);
                   } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to host.");
                System.exit(1);
              //Send file over Socket
            //===========================================================
            BufferedInputStream fileIn = null;
              BufferedOutputStream out = null;
              // File to be send over the socket.
              File file = new File("c:/xampp/htdocs/thesis/sensorList.php");
              // Checking for the file to be sent.
              if (!file.exists())
                   System.out.println("File doesn't exist");
                   System.exit(0);
              try
                   // InputStream to read the file
                   fileIn = new BufferedInputStream(new FileInputStream(file));
              }catch(IOException eee)
                   System.out.println("Problem, kunne ikke lage fil");
              try
                   InetAddress adressen = InetAddress.getByName(host);
                   try
                        System.out.println("Establishing Socket Connection");
                        // Opening Socket
                        Socket s = new Socket(adressen, port);
                        System.out.println("Socket is clear and available.....");
                        // OutputStream to socket
                        out = new BufferedOutputStream(s.getOutputStream());
                        byte[] buffer = new byte[1024];
                        int numRead;
                        //Checking if bytes available to read to the buffer.
                        while( (numRead = fileIn.read(buffer)) >= 0)
                             // Writes bytes to Output Stream from 0 to total number of bytes
                             out.write(buffer, 0, numRead);
                        // Flush - send file
                        out.flush();
                        // close OutputStream
                        out.close();
                        // close InputStrean
                        fileIn.close();
                   }catch (IOException e)
              }catch(UnknownHostException e)
                   System.err.println(e);
            //===========================================================
            //Retrieve data from Socket.
              //BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
              DataInputStream in = new DataInputStream(new BufferedInputStream(toServer.getInputStream()));
              //String fromServer;
            //Read from the server and prints.
              //Receive text from server
              FileWriter fr = null;
              String frn = "xxx_response.xml";
              try {
                   fr = new FileWriter(frn);
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              try{
                   String line = in.readUTF();                    //.readLine();
                   System.out.println("Text received :" + line);
                   fr.write(line);
              } catch (IOException e){
                   System.out.println("Read failed");
                   System.exit(1);
            in.close();
            toServer.close();
    public class XMLSocketS
          public static void main(String[] args) throws IOException
              //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4444);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
              while (true)
                        try
                             clientLink = serverSocket.accept();
                           System.out.println("Server accepts");
                             BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             // close the link to client
                             clientLink.close();                         
                             // close InputStream
                             inn.close();                         
                             // flush
                             ut.flush();                         
                             // close OutputStream
                             ut.close();     
                             //Sending response to client     
                             //============================================================
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
    }

    SERVER
    import java.net.*;
    import java.io.*;
    public class XMLSocketS
          public static void main(String[] args) throws IOException
                   //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4545);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
                  try
                             clientLink = serverSocket.accept();
                         System.out.println("Server accepts the client request.....");
                         BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             ut.flush();                         
                             //Sending response to client     
                             //============================================================
                             BufferedInputStream ftoC = null;
                             BufferedOutputStream outtoC = null;
                             // File to be send over the socket.
                             File file = new File("c:/xampp/htdocs/thesis/user_registration_response.xml");
                             try
                                  // InputStream to read the file
                                   ftoC = new BufferedInputStream(new FileInputStream(file));
                             }catch(IOException eee)
                             {System.out.println("Problem reading file");}
                             // OutputStream to socket
                             outtoC = new BufferedOutputStream(clientLink.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int noRead;
                             //Checking if bytes available to read to the buffer.
                             while( (noRead = ftoC.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  outtoC.write(buffer, 0, noRead);
                             outtoC.flush();
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
          }CLIENT SIDE
    import java.io.*;
    import java.net.*;
    public class XMLSocketC
              @SuppressWarnings("deprecation")
              public static void main(String[] args)
                   // Server: "localhost" here. And port to connect is 4545.
                   String host = "127.0.0.1";          
                   int port = 4545;
                   BufferedInputStream fileIn = null;
                   BufferedOutputStream out = null;
                   // File to be send over the socket.
                   File file = new File("c:/xampp/htdocs/thesis/sensorList.xml");
                   try
                        // InputStream to read the file
                        fileIn = new BufferedInputStream(new FileInputStream(file));
                   }catch(IOException eee)
                   {System.out.println("Problem");}
                   try
                             System.out.println("Establishing Socket Connection");
                             // Opening Socket
                             Socket clientSocket = new Socket(host, port);
                             System.out.println("Socket is clear and available.....");
                             // OutputStream to socket
                             out = new BufferedOutputStream(clientSocket.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int numRead;
                             //Checking if bytes available to read to the buffer.
                             while( (numRead = fileIn.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  out.write(buffer, 0, numRead);
                             // Flush - send file
                             out.flush();
                             //=======================================
                             DataInputStream in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                             BufferedWriter outf = new BufferedWriter(new FileWriter("c:/xampp/htdocs/received_from_server.txt",true));
                             String str;
                             while(!(str = in.readLine()).equals("EOF")) {     
                                  System.out.println("client : Read line -> <" + str + ">");
                                  outf.write(str);//Write out a string to the file
                                  outf.newLine();//write a new line to the file (for better format)
                                  outf.flush();
                             //=======================================
                             // close OutputStream
                             out.close();
                             // close InputStrean
                             fileIn.close();
                             // close Socket
                             clientSocket.close();
                        }catch (IOException e)
                        {System.out.println("Exception.");}
         Could you please point where am I doing the stupid mistake, client to server is working properly, but the opposite direction is not.
    Thanks

  • Client/server socket based application

    hi does anyone have example of client/server socket based application using Spring and Maven
    where application do the following
    Client sends a request with a path to any file on the server
    „h Server reads the file and responds back with the content
    „h Client outputs the content to the console
    am trying to follow this
    http://www2.sys-con.com/itsg/virtualcd/java/archives/0205/dibella/index.html
    http://syntx.io/a-client-server-application-using-socket-programming-in-java/
    am using java 6

    i have attempt code but i wht to do the following
    client/server socket based application that will read the content of a file and stream the content of the file to the client. The client must simply output the content of the file to the console using System.out. The client must be able to run in a standalone mode (non-network mode) or in a remote mode.
    Additionally the client must be designed in a way that i can print the output to a console but must be interchangeable where if requirements change i can persist the response to file or persist the response to a database.
    /* Server.java*/
    ///ifgetBoolen= true then...
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.sql.*;
    public class Server
        static String array[][];
        // STEP 1 a1  
        // Server socket
        ServerSocket listener;
        // STEP 1 a2 Client connection
        Socket client;
        ObjectInputStream in;
        ObjectOutputStream out;
        public void createConnection() throws IOException
                System.out.println("\nSERVER >>> Waiting for connection.....");
                client = listener.accept();
                String IPAddress = "" + client.getInetAddress();
                DisplayMessage("SERVER >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
          public void runServer()
            // Start listening for client connections
            // STEP 2
            try
                listener = new ServerSocket(12345, 10);
                createConnection();
                  // STEP 3
    //              processConnection();
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Error trying to listen: " + ioe.getMessage());
        private void closeConnection()
            DisplayMessage("SERVER >>> Terminating connections");
            try
                if(out != null && in != null)
                      out.close();
                    in.close();
                    client.close();                
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Closing connections");
        public static void define2DArray(ResultSet RS, int Size)
            try
                ResultSetMetaData RMSD = RS.getMetaData();
                DisplayMessage("SERVER >>> Requested arraySize: " + Size);
                if (RS.next())
                    array = new String[Size][RMSD.getColumnCount()];
                    for (int Row = 0; Row < Size; Row++)
                        for (int Col = 0; Col < RMSD.getColumnCount(); Col++)
                            array[Row][Col] = new String();
                            array[Row][Col] = RS.getString(Col+1);
                            DisplayMessage(array[Row][Col] + " ");
                        RS.next();
                else
                    array = new String[1][1];
                    array[0][0] = "#No Records";
            catch (Exception e)
                DisplayMessage("SERVER >>> Error in defining a 2DArray: " + e.getMessage());  
        public static void DisplayMessage(final String IncomingSMS)
            System.out.println(IncomingSMS);
    //client
    * @author
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class ClientSystem
        static Socket server;
        static ObjectOutputStream out;
        static ObjectInputStream in;
        static String Response[][];
        static boolean IsConnected = false;
        static int Num = 0;
        public static void connectToServer() throws IOException
            server = new Socket("127.0.0.1", 12345);
    //        server = new Socket("000.00.98.00", 12345);
            String IPAddress = "" + server.getInetAddress();
            DisplayMessage("\nCLIENT >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
        public static void getStreams() throws IOException
            out = new ObjectOutputStream(server.getOutputStream());
            out.flush();
              in = new ObjectInputStream(server.getInputStream());
              IsConnected = true;
              DisplayMessage("CLIENT >>> Got I/O streams");  
        public static void runClient()
            try
                connectToServer();
                getStreams();
                  DisplayMessage("CLIENT >>> Connection successfull....\n");
                  DisplayMessage("CLIENT >>> Want to talk to server");
            catch (IOException ioe)
                System.out.print("."+Num);
                Num++;
        public static void closeConnection()
            try
                out.close();
                in.close();
                server.close();  
            catch(IOException error)
                DisplayMessage("CLIENT >>> Could not close connections");
        public static void Start()
            System.out.print("\nCLIENT >>> Attempting connection.....");
            try
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    if (IsConnected == false)
                        Thread.sleep(100);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Attempting connection.....");
        public static String sendSMS(String sms)
            Response = new String[0][0];
            try
                DisplayMessage("CLIENT >>> " + sms);
                out.writeObject(sms);
                out.flush();
                Response = (String[][])in.readObject();
                DisplayMessage("CLIENT >>> Waiting for server to respond...");
                for (int Row = 0; Row < Response.length; Row++)
                    System.out.printf( "_SERVER >>> \t");
                    for (int Col = 0; Col < Response[Row].length; Col++)
                        //DisplayMessage( "_SERVER >>> " + Response[Row][Col] + " ");
                        System.out.printf( "%s\t", Response[Row][Col]);
                    System.out.println();
                DisplayMessage("CLIENT >>> Query processed successfully....\n");
            catch(ClassNotFoundException cnfe)
                DisplayMessage("CLIENT >>> Class not found for casting received object");
            catch(IOException ioe)
                reConnect();          
            catch (Exception sqle)
                DisplayMessage("CLIENT >>> Error sending query ??? " + sqle.getMessage());
            return "transmission successfull";
        public static void reConnect()
            try
                DisplayMessage("CLIENT >>> Connection was lost. Trying to reconnect...");
                closeConnection();
                Thread.sleep(100);
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    Thread.sleep(200);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Error trying to Re-Connect...");
        public static void DisplayMessage(final String IncomingSms)
            System.out.println(IncomingSms);
        System.out.printf("Isms: %s", IncomingSms);  ///naah.
        public static String[][] getResponse()
            return Response;
        public static String getResponse(int row, int col)
            return Response[row][col];
    how can i do below using above code
    The program must be able to work in a non-networked mode. In this mode, the server and client must run in the same VM and must perform no networking, must not use loopback networking i.e: no “localhost” or “127.0.0.1”, and must not involve the serialization of any objects when communicating between the client and server components.
    The operating mode is selected using the single command line argument that is permitted.
    imust use a socket connection and define a protocol. networking must be entirely bypassed in the non-network mode.

  • Client/server RMI app using Command pattern: return values and exceptions

    I'm developing a client/server java app via RMI. Actually I'm using the cajo framework overtop RMI (any cajo devs/users here?). Anyways, there is a lot of functionality the server needs to expose, all of which is split and encapsulated in manager-type classes that the server has access to. I get the feeling though that bad things will happen to me in my sleep if I just expose instances of the managers, and I really don't like the idea of writing 24682763845 methods that the server needs to individually expose, so instead I'm using the Command pattern (writing 24682763845 individual MyCommand classes is only slightly better). I haven't used the command pattern since school, so maybe I'm missing something, but I'm finding it to be messy. Here's the setup: I've got a public abstract Command which holds information about which user is attempting to execute the command, and when, and lots of public MyCommands extending Command, each with a mandatory execute() method which does the actual dirty work of talking to the model-functionality managers. The server has a command invoker executeCommand(Command cmd) which checks the authenticity of the user prior to executing the command.
    What I'm interested in is return values and exceptions. I'm not sure if these things really fit in with a true command pattern in general, but it sure would be nice to have return values and exceptions, even if only for the sake of error detection.
    First, return values. I'd like each Command to return a result, even if it's just boolean true if nothing went wrong, so in my Command class I have a private Object result with a protected setter, public getter. The idea is, in the execute() method, after doing what needs to be done, setResult(someResult) is called. The invoker on the server, after running acommand.execute() eventually returns acommand.getResult(), which of course is casted by the client into whatever it should be. I don't see a way to do this using generics though, because I don't see a way to have the invoker's return value as anything other than Object. Suggestions? All this means is, if the client were sending a GetUserCommand cmd I'd have to cast like User user = (User)server.executeCommand(cmd), or sending an AssignWidgetToGroup cmd I'd have to cast like Boolean result = (Boolean)server.executeCommand(cmd). I guess that's not too bad, but can this be done better?
    Second, exceptions. I can have the Command's execute() method throw Exception, and the server's invoker method can in turn throw that Exception. Problem is, with a try/catch on the client side, using RMI (or is this just a product of cajo?) ensures that any exception thrown by a remote method will come back as a java.lang.reflect.InvocationTargetException. So for example, if in MyCommand.execute() I throw new MySpecialException, the server's command invoker method will in turn throw the same exception, however the try/catch on the client side will catch InvocationTargetException e. If I do e.getCause().printStackTrace(), THERE be my precious MySpecialException. But how do I catch it? Can it be caught? Nested try/catch won't work, because I can't re-throw the cause of the original exception. For now, instead of throwing exceptions the server is simply returning null if things don't go as planned, meaning on the client side I would do something like if ((result = server.executeCommand(cmd)) == null) { /* deal with it */ } else { /* process result, continue normally */ }.
    So using the command pattern, although doing neat things for me like centralizing access to the server via one command-invoking method which avoids exposing a billion others, and making it easy to log who's running what and when, causes me null-checks, casting, and no obvious way of error-catching. I'd be grateful if anyone can share their thoughts/experiences on what I'm trying to do. I'll post some of my code tomorrow to give things more tangible perspective.

    First of all, thanks for taking the time to read, I know it's long.
    Secondly, pardon me, but I don't see how you've understood that I wasn't going to or didn't want to use exceptions, considering half my post is regarding how I can use exceptions in my situation. My love for exception handling transcends time and space, I assure you, that's why I made this thread.
    Also, you've essentially told me "use exceptions", "use exceptions", and "you can't really use exceptions". Having a nested try/catch anytime I want to catch the real exception does indeed sound terribly weak. Just so I'm on the same page though, how can I catch an exception, and throw the cause?
    try {
    catch (Exception e) {
         Throwable t = e.getCause();
         // now what?
    }Actually, nested try/catches everywhere is not happening, which means I'm probably going to ditch cajo unless there's some way to really throw the proper exception. I must say however that cajo has done everything I've needed up until now.
    Anyways, what I'd like to know is...what's really The Right Way (tm) of putting together this kind of client/server app? I've been thinking that perhaps RMI is not the way to go, and I'm wondering if I should be looking into more of a cross-language RPC solution. I definitely do want to neatly decouple the client from server, and the command pattern did seem to do that, but maybe it's not the best solution.
    Thanks again for your response, ejp, and as always any comments and/or suggestions would be greatly appreciated.

  • Need HELP in JAVA ( client /server application )

    hi there ,
    I need the following codes in java for my client/server application . which i can use to perform certain function on another computer on LAN. This is part of my semester project . I would really appreciate if any one can help me
    ->Open/close the CD-ROM once or in intervals (specified in seconds).
    ->Swap mouse buttons the right mouse button gets the left mouse button's functions and vice versa.
    ->Start optional application.
    ->Play optional sound-file.
    ->Point the mouse to optional coordinates.
    ->Shutdown the system, logoff the user etc.
    ->Mouse can be controlled on the target computer with remote mouse.
    ->Keys (letters) on the keyboard can be disabled.
    ->Increase and decrease the sound-volume.
    ->Listen for keystrokes and send them back to you!
    I would really appreciate if some1 can help me find these codes in java
    thanx
    Alamzaib Shafi
    [email protected]

    Dude, if you did your own homework once in a while you'd be able to handle your own semester project. I hope you fail your class and get kicked out of the program. One less idiot with a diploma competing with us hackers for the tech jobs.
    You are indeed a most worthy recipient of my unemployed angst.

Maybe you are looking for

  • Totally confused about product names/functionality

    The product "ZENWorks Desktop Management 7" includes functionality called "Asset Management" The product "ZENWorks Asset Management" is also a product about "collection information of devices and software". Now Novell introduced the product "ZENWorks

  • HP Deskjet 840c not printing properly on tiger 10.4.8 using gimp

    Hi new to macs.1 connected my printer via usb and tiger automatically recognised it.2 went to print and and some of the print was missing and incorrect characters appeared. 3 thought the driver was at fault so reloaded it from back up dvd. 4 didnt wo

  • Psc 1350 all in one installing hp solution center

    I am trying to find and install the full installation for this printer. I wish to use the hp Solution Center.

  • Help with a simple iterator question

    the question is how to reset an iterator so it points to the beginng of a collection. Here is a piece of code. Thanks in advance: import java.io.*; import java.util.*; public class IteratorTest { public static void main(String[] args) { List list = n

  • ITunes music library not completely syncing with my iPod touch??

    I have restored my iPod, uninstalled and reinstalled iTunes.  When I look at the file structure, there are multiple folders with music in them, not all consistent.  Any ideas what I could do to get all the music where it is supposed to be.  My librar