Design Pattern for multithreaded client server program

I asked this question in another post, but with other stuff, so I'll distill this one.
I am creating a multi-threaded client server program (just for learning - a chat program at this point). I built the server and client in swing, and I'm wondering what the best design pattern is for this setup. Right now all the swing stuff is in the MyServer class. In that class I have a loop accepting client connections to the serverSocket and creating a new MyServerThread (threaded client connection).
The problem is that all the work of creating input streams, interacting with the server, all that stuff is done in the MyServerThread class, but I want that text to be written up to the Swing objects - which is in the MyServer class. So right now in the MyServerThread class I pass the MyServer object into it, but I'm not sure if that is really the most robust thing to do. Does anybody have any suggestions as to how this should be done. If somebody has an article they'd like to point to I'll check it out too. But if it's just the run-of-the-mill multithreaded client-server article, I've read alot and most don't specifically address my question.

Thanks for the reply Kaj, and I think I'll keep my design for now, since it's just quick and dirty. I've read the MVC concept a while ago and I'll revisit it again when I get more serious. But I have a question, why should I be using a callback interface, why an interface at all? And then make MyServer implement that interface...why not just pass MyServer to the thread object? Or is there something down the line that I did not forsee?

Similar Messages

  • Client Server program using Applets for client

    Creating a client server program using Applets for the clients.
    Having problems distrubting the message from client to client
    using ObjectOutputStreams/ObjectInputSteams.
    I can connect each client to simple server and respond with by writting
    the i/o stream of each client but unable to communicate from client to client. If any one out there has in tips of creating a class of objectOutputStreams that holds a array of ObjectOutputStreams and then broadcasts the message to every client, it would be much appreciated
    Thanks.

    Cheers poop for your reply
    I never explained the problem properly. What it is I am trying to set up a Client Server program using Applets as the clients GUI. The problem is broadcasting the message to multiply client connnection(s).
    Below is code, each client can connect and send message to the server. The problems is broadcasting the message to every client connection. The every client can input a message but only the last connected client can receive the message?????? Thanks in advance..
    /*this my server class */
    import java.io.*;
    import java.net.*;
    public class Server extends JFrame
    private static final int ServerPort=8080;
    private static final int MaxClients=10;
    private ObjectOutputStream output=null;
    private ObjectInputStream input=null;
    private BroadCastMessage broadcastMessage;
    public void runServer()          
    BroadCastMessage broadcastMessage= new BroadCastMessage();
    try
    {  //connect to server
    ServerSocket s = new ServerSocket(ServerPort,MaxClients);
         //listen to port 5000 for new connections
         ///max is 25
         System.out.println("Server listening on port "+ServerPort);
    while (state.isProgramRunning())
         try
         /// sGUI.waitForConnection();//new line
         s.setSoTimeout(100);
         //enable times in server-socket
         while (true)     
         Socket incoming = s.accept();
         //wait and accept connnections from serverSocket
         //instance of the class,pases the new connection and message
         //spawn as a thread
         SocketConnection connection=new SocketConnection(incoming,broadcastMessage);
         Thread a = new Thread(connection); a.start();
         System.out.println(state.getConnectionCount()+"Connection received from :"+incoming.getInetAddress());
         catch(InterruptedIOException x){}
    while (state.getConnectionCount()>0);
    System.exit(0);
    }catch (IOException e){}
    public static void main(String[] args)
    Server s =new Server();
         s.runServer();
    /*this is my socket connection thread*/
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    public class SocketConnection implements Runnable
    private ObjectOutputStream out;
    private ObjectOutputStream output=null;
    private ObjectInputStream input=null;
    private BroadCastMessage passOnMessage;
    private Socket theConnection=null;
    private String Inmessage="";
    private int Ocount;
    public SocketConnection(Socket caller,BroadCastMessage broadcastMessage,Ocount)
    theConnection =caller;///(5000,n)
    Ocount=ncount;
    passOnMessage=broadcastMessage;
    public void run()
    try
    getStreams();
    processConnection();
    catch(Exception e)
    {String clientDetails=("connection from IP Address: "+theConnection.getInetAddress());}
    private synchronized void getStreams() throws IOException
    { //get streams to send and receive data
    //set up output buffer to send header information
    ///Ocount++;
    //create new objectoutputstream
    output=passOnMessage.getOutputObject(output,theConnection,Ocount);
    ///flush output buffer to send header info.
    Ocount++;
    //set up input stream for objects
    input =new ObjectInputStream(
    theConnection.getInputStream());
    System.out.print("\nGot I/O streams\n");
    private synchronized void processConnection()throws IOException
    //process connection with client
    String Outmessage =" count : "+status.getConnectionCount();
    //send connection successful message to client
         Outmessage=Outmessage+"SERVER>>>Connection successful";
         output.writeObject(Outmessage);
    output.flush();
    do ///process messages sent from client
         try
         Inmessage = (String) input.readObject();
         System.out.println(Inmessage);
         /* //while the connection is open each line
         that is passed from the client to the server
         is read in and is displayed*/
         messageDetails.setMessage(Inmessage);
         String CurrentMessage=messageDetails.getMessage();
         //output.writeObject(CurrentMessage);
         // output.flush();
         passOnMessage.FloodMessage(CurrentMessage);
         //sending out the message
    catch(ClassNotFoundException classNotFoundException){}
    }while (!Outmessage.equals("CLIENT>>>TERMINATE"));
    /*this my attempt at broadcasting the message to all clients
    my thinking was that you could create a array of objectoutputstreams
    which in turn could be broadcasted(bit confussed here)*/
    import java.io.*;
    import java.net.*;
    public class BroadCastMessage /// implements Runnable
    private int count;
    private String Inmessage="";
    private ObjectOutputStream temp=null;
    private ObjectOutputStream[] output = new ObjectOutputStream [12];
    //temp level of array of objects
    public BroadCastMessage()
    count=0;
    public synchronized void FloodMessage(String message) throws IOException
    System.out.print(count);
         for(int i=0;i<count+1;i++)
         try
    {  System.out.print(count);
         output[count].writeObject(message);
         output[count].flush();
         catch(IOException ioException)
    {ioException.printStackTrace();}
         notifyAll();
    public ObjectOutputStream getOutputObject(ObjectOutputStream out,Socket caller,int Ocount)
    try
    { temp = new ObjectOutputStream(caller.getOutputStream());
         AddObjectOutputStream(temp,Ocount);
    ////FloodMessage();
         catch(IOException ioException)
    {ioException.printStackTrace();}
    return temp;     
    public void AddObjectOutputStream(ObjectOutputStream out,int Ocount)
    { ///add new object to array
    count=Ocount;
    output[count]=out;
    System.out.print("\nthe number of output streams : "+count+"\n");
    }

  • Design Patterns for java swing application front a J2EE server

    Hi,
    i dont nkow that i stay in the correct forum. I am development a java swing client application, no web, and i dont know that if there are any patterns for a client of this type.
    I have readed http://java.sun.com/blueprints/corej2eepatterns/Patterns/index.html
    but after of Buissnes Delegate pattern, the others one, over ejb tier, are applicated only for web clients, using servlets and jsp pages.
    If i have a swing client application, what patterns i must folow for implement the client logic of my swing application??
    thanks

    MVC pattern is one of the most used
    http://en.wikipedia.org/wiki/MVC
    http://csis.pace.edu/~bergin/mvc/mvcgui.html
    ...

  • Is there a design pattern for this?

    I'm looking for a solution to a design problem I have.
    For a restaurant booking system I need a number of different opening times describing when you can and cannot book. These opening times are essentially Jodatime Period objects. There's a set of opening times spanning a week and these are repeated for every week (a default set of opening times) however it's possible to override these opening times say for a specific day.
    The domain model would be something like a Restaurant class holding 2 Lists of OpeningTime objects one for defaultOpeningTimes and the other for overiddenOpeningTimes the overidden ones get used if they exist for the requested time period. However the database model would be a bit messy as I'd have 2 lists mapping to the same table (OpeningTime). Is that a good idea? Perhaps there's a design pattern for this, if someone could point me in the right direction I'd be very grateful, or perhaps this is the best solution? Thanks!

    jduprez wrote:
    But why do you put the logic in the database too (I'm no DB expert and I didn't know these concepts until I read your post, but that's what a dynamic view based on derived values looks like to me): performance (1 round-trip instead of two)?Hi jduprez. Long time no speakee.
    I guess part of it is that I spent many years as a DBA and modeller, and really appreciate what it's taught me about design. Also, databases are (or should be) designed from the ground up to provide data-directed requests optimally, and include all sorts of nice stuff like transaction handling that aid consistency, as well as speed.
    That said: I HATE SQL. Think Coliseum, with that emblazoned in 60-foot high letters around its walls, and it might come close to just how much I hate that so-called "language". I hate its form; I hate it's inconsistencies; I hate the fact that something like what OP is trying to do is NOT an easy task (and might involve the creation of a table that simply contains Dates, just in order to satisfy Boolean logic).
    However, once you work it out, a database view (at least from the database's standpoint; JDBC I'm not so sure about) is just like any other Table - and that I DO like.
    Programs are good at processing parameterized (ugh) temporal information; databases are good at persistence and high volume. Those two may meet at some point, but I reckon it's going to take another Codd (or Joda) before it does.
    - that's clearer to 90% of the dev team (my biased numbers, based on 50% of Java developers having decent knowledge of SQL and much less than that having the advanced SQL knowledge which I rank your suggestion at)Sounds to me like you'll get the solution that matches the skills you have then. Is that what you really want, if a better one is available?
    - that doesn't require investigating the if of your suggestion (JDBC support)Agreed, but only because my JDBC knowledge isn't what it could be. I'd also be surprised if it doesn't support access to a named view, since they were designed to be equivalent to Tables.
    - the Op is using DAOs, so it's possible, if profiling does show this is hampering performances, to change that with no impact on the client code that calls the DAO.There's no doubt that a database solution is much higher level than a programming one; but, as I said, it's what they were designed to do. And tinkering around with program optimization has the feel of a "hacker's solution" to me. Not that there's any particular problem with that - I do it quite often when I have no control over my source - but I also try to keep in mind what the "actual" problem is.
    Winston

  • Design Pattern for execution queue

    Anyone know of any good design patterns for using a JMS Queue and MDB's
              as async
              execution queue which maintains execution order by some key
              

    Enforced ordering on redelivery will be supported in the
              next release, but only if the application clamps the pipe-line
              size down to its minimum and the MDB pool size down to one.
              I don't think enforced ordering is supported in the current release.
              We are looking at least partially addressing the general design
              pattern below in the release after next. I don't think I can
              get away with being more specific. (Sorry.) Currently, I
              think something along the line of Larry's solution is the only way to
              accomplish it. Interestingly, the recent thread started
              by "[email protected]" on correlating requests and responses
              seems to be somewhat related.
              Tom, BEA
              Larry Presswood wrote:
              > Well you are both correct however we have something which works
              > however it does involve some threading primitives which generally is not
              > a good idea
              > inside wlas but seems to work.
              >
              >
              > Generally have a singleton on the server which has slots for each key
              > with message
              > numbering for each message and force a wait if message for key is out of
              > order
              > during fifo processing rules. IE do what things you can do in parallel
              > but gate for
              > the last step.
              >
              > I think there is a general remote execution pattern out there.
              >
              > The general problem to solve is this:
              >
              > In a messaging system you want to process messages for each key/session
              > in order however
              > with a large number of sessions its possible to parallel messages for
              > different sessions
              >
              > Otherewise you can either create custom queues or a topic with a
              > selector and then
              > create custom consumers which does not behave as well from a resource
              > perspective
              > as MDB's do.
              >
              >
              >
              >
              >
              >
              >
              > Nick Minutello wrote:
              >
              >>I may be completely wrong - but I think that Larry is referring to the inherant
              >>out-of-order message consumption that you get when using MDB pools to consume
              >>from a Queue.
              >>
              >>In short, the only design pattern here is to deploy the MDB to only one machine
              >>in the cluster - and set the pool size to 1.
              >>
              >>In-order execution is incompatible with the parallel execution that MDB's give
              >>you.
              >>
              >>-Nick
              >>
              >>
              >>
              >>Tom Barnes <[email protected]> wrote:
              >>
              >>
              >>>Hi Larry,
              >>>
              >>>Generally, I think it is best to have a seperate queue per key if the
              >>>
              >>>number of keys is small. This prevents starvation of a particular
              >>>message. For example when handling message-priority, low priority gets
              >>>
              >>>an MDB pool of size 1, high priority gets and MDB pool of size 10.
              >>>
              >>>Note that WebLogic JMS allows a queue to specify a sort-order keys based
              >>>on arbitrary message fields. Note that the in-flight message pipe-line
              >>>
              >>>between server and asynchronous clients is unsorted.
              >>>
              >>>Tom, BEA
              >>>
              >>>Larry Presswood wrote:
              >>>
              >>>
              >>>>Anyone know of any good design patterns for using a JMS Queue and MDB's
              >>>>
              >>>>
              >>>>as async
              >>>>execution queue which maintains execution order by some key
              >>>>
              >>>>
              >>>>
              >>
              >>
              >>
              >
              

  • Flex design pattern for BlazeDS transfer objects

    Dear Community,
    I have a question regarding the nature of objects transferd from BlazeDS backend to the Flex client.
    According to some adobe docs all the presentation logic should be in flex and BlazeDS should provide only services.
    The question is what kind of transfer objects should be used? with what level of abstraction?
    To make it more clear let's talk about a simple forum application like adobe forums.
    I have created a Forum service, which returns a Forum transfer object, which has a List of Threads, with each thread having a List of Messages.
    Flex gets the Forum transfer object and does all the presentaiton work.
    This is a very nice seperatin of concerns architecture BUT there are two major performance issues:
    - when the forum becomes bigger the transfer object will be huge
    - the flex will use huge client resources to create the presentation of the forum transfer object.
    So my question is what is your strategy/ design pattern for such a problem.
    An obvious answer would be create services that include the presentation logic and use transfor objects like ThreadListPage which will include only the first 10 threads.
    Thanks in advance

    I think you are going to get a few varied types of answers to a general question like this, but I will comment on a few things.  First, you should only be transmitting the data that you need to use or display to the user at the time.  If this forum was implemented in Flex (I wish) you wouldn't transfer the text for all the threads.  You might not transfer the thread text at all (just the subjects), you'd make calls back to the server to fetch that data when and if you need it.
    Also, I think you are overestimating the resources required for the Flex "presentation layer".  If you think about it, these workstations we have here are pretty idle most of the time when you're at a website.  Nowadays there's plenty of processing power just sitting there waiting, so as long as your design isn't flawed the CPU or memory are rarely going to be a bottleneck with Flex.
    The way I design, BlazeDS (or GraniteDS etc) should mostly just be "serving data".  There is some flexibility available, for example I don't see a problem with putting certain types of business rules (such as a limit on the number of results that can be recieved in a search) within server side code, and validation rules on the Flex side.  So there's not too many "industry standards" in Flex yet beyond maybe what's done in the various standard architectures, at least not that I'm aware of.
    You might find it beneficial to look into some of the various frameworks/architectures available like Cairngorm, Mate, Swiz, and so on.  Learning how they work (looking at examples) would probably answer some of your questions too.

  • Choice of design pattern for data acquisition system

    Hello all
    I have a trouble about selecting the suitable design pattern / architecture for a data acquisition system. 
    Here is the details of the desired system:
    There is data acquisition hardware and I need to use it by observing parameters on User interface. 
    the data acquisiton period, channel list to scan should be chosen on User interface. Besides, there are many user interface interactions. e.g. if user selects a channel to add scanlist, then I need to enable and make visible some other parts on user interface. 
    When user completes the channel selection, then he will press the button to start data acquisition. Then I also need to show the scanned values on a graph in real time and log them in txt file.
    I know that I cannot use producer consumer pattern here. because the data acquisition loop should wait for parameters to scan channels. and it works in a given period by user. so the user interface loop performs higher rate then consumer loop (data acquisition loop). it means queue will be bigger bigger. if I use notifier it will loss some data come from user interface. 
    is there any idea about that ? is there any suitable design pattern for this case ? 
    Thanks in advance
    best regards 
    Veli BAYAR
    Embedded Systems Software and Hardware Engineer 
    "You live in a graphical world. Why not program in one?"
    Solved!
    Go to Solution.

    johnsold wrote:
    Veli,
    I recommend the Producer/Consumer model with some modifications.
    You might need three loops.  I cannot tell for sure from your brief description.
    The User Interface loop responds to the user inputs for configuration and start/stop of acquisition.  The parameters and commands are passed to the Data Acquisition loop via a queue. In this loop is a state machine which has Idle, Configuration, Acquisition, and Shutdown states (and perhaps others). The data is sent to the Processing loop via a different queue. The Processing loop performs any data processing, displays the data to the user, and saves it to file. A notifier can be used to send the Stop or shutdown command from the User Interface loop to the other loops.  If the amount of processing is minimal and the file write times are not too long, the Processing loop functions might be able to occur in the Timeout case of the UI loop Event structure.  This simplifies things somewhat but is not as flexible when changes need to be made.
    I am not sure that a Design Pattern for this exact setup exists but it is basically a combination of the Producer/Consumer (Events) and Producer/Consumer (Data) Design Patterns.
    Lynn
    Check out this thread: http://forums.ni.com/t5/LabVIEW/Multiple-poll-case-structures-to-event-help/td-p/2551309
    There are discussions there about a 3-loop architecture that may help you.
    Jeff
    Jeffrey Zola

  • 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 programming

    Hi;
    I want to learn client server programming on using windows xp for the client and windows server 2003.
    I downloaded the 9.2 windows xp database version for the client . What do I need to download for the server? I see that there is a 32 and 64 bit version for the server.
    Thanks for your help!

    What I was asking is what should I install on the server
    the 32 or 64 bit version of oracle?
    I want to learn how to write client/server programs using Oracle.
    I have a network at home with one computer serving as the client and another has server 2003 on it.
    Again Thanks for your help!

  • Help with MIDlets - TCP client server program

    Hi I am new to using MIDlets, and I wanted to create a simple TCP client server program.. I found a tutorial in J2me forums and I am able to send a single message from server(PC) to client(Phonemulator) and from client to server. But I want to send a stream of messages to the server. Here is my program and I am stuck in the last step wher i want to send lot of messages to server. Here is my program, Could any one of u tell me how to do it? Or where am i going wrong in thsi pgm?
    Code:
    import java.io.InputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import javax.microedition.io.Connector;
    import javax.microedition.io.SocketConnection;
    import javax.microedition.io.StreamConnection;
    import javax.microedition.lcdui.Alert;
    import javax.microedition.lcdui.AlertType;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Form;
    import javax.microedition.lcdui.StringItem;
    import javax.microedition.lcdui.TextField;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.midlet.MIDletStateChangeExcepti on;
    public class SocketMIDlet extends MIDlet
    implements CommandListener, Runnable {
    private Display display;
    private Form addressForm;
    private Form connectForm;
    private Form displayForm;
    private TextField serverName;
    private TextField serverPort;
    private StringItem messageLabel;
    private StringItem errorLabel;
    private Command okCommand;
    private Command exitCommand;
    private Command backCommand;
    protected void startApp() throws MIDletStateChangeException {
    if (display == null) {
    initialize();
    display.setCurrent(addressForm);
    protected void pauseApp() {
    protected void destroyApp(boolean unconditional)
    throws MIDletStateChangeException {
    public void commandAction(Command cmd, Displayable d) {
    if (cmd == okCommand) {
    Thread t = new Thread(this);
    t.start();
    display.setCurrent(connectForm);
    } else if (cmd == backCommand) {
    display.setCurrent(addressForm);
    } else if (cmd == exitCommand) {
    try {
    destroyApp(true);
    } catch (MIDletStateChangeException ex) {
    notifyDestroyed();
    public void run() {
    InputStream is = null;
    OutputStream os = null;
    StreamConnection socket = null;
    try {
    String server = serverName.getString();
    String port = serverPort.getString();
    String name = "socket://" + server + ":" + port;
    socket = (StreamConnection)Connector.open(name, Connector.READ_WRITE);
    } catch (Exception ex) {
    Alert alert = new Alert("Invalid Address",
    "The supplied address is invalid\n" +
    "Please correct it and try again.", null,
    AlertType.ERROR);
    alert.setTimeout(Alert.FOREVER);
    display.setCurrent(alert, addressForm);
    return;
    try {
    // Send a message to the server
    String request = "Hello\n\n";
    //StringBuffer b = new StringBuffer();
    os = socket.openOutputStream();
    //for (int i=0;i<10;i++)
    os.write(request.getBytes());
    os.close();
    // Read the server's reply, up to a maximum
    // of 128 bytes.
    is = socket.openInputStream();
    final int MAX_LENGTH = 128;
    byte[] buf = new byte[MAX_LENGTH];
    int total = 0;
    while (total<=5)
    int count = is.read(buf, total, MAX_LENGTH - total);
    if (count < 0)
    break;
    total += count;
    is.close();
    String reply = new String(buf, 0, total);
    messageLabel.setText(reply);
    socket.close();
    display.setCurrent(displayForm);
    } catch (IOException ex) {
    Alert alert = new Alert("I/O Error",
    "An error occurred while communicating with the server.",
    null, AlertType.ERROR);
    alert.setTimeout(Alert.FOREVER);
    display.setCurrent(alert, addressForm);
    return;
    } finally {
    // Close open streams and the socket
    try {
    if (is != null) {
    is.close();
    is = null;
    } catch (IOException ex1) {
    try {
    if (os != null) {
    os.close();
    os = null;
    } catch (IOException ex1) {
    try {
    if (socket != null) {
    socket.close();
    socket = null;
    } catch (IOException ex1) {
    private void initialize() {
    display = Display.getDisplay(this);
    // Commands
    exitCommand = new Command("Exit", Command.EXIT, 0);
    okCommand = new Command("OK", Command.OK, 0);
    backCommand = new Command("Back", Command.BACK, 0);
    // The address form
    addressForm = new Form("Socket Client");
    serverName = new TextField("Server name:", "", 256, TextField.ANY);
    serverPort = new TextField("Server port:", "", 8, TextField.NUMERIC);
    addressForm.append(serverName);
    addressForm.append(serverPort);
    addressForm.addCommand(okCommand);
    addressForm.addCommand(exitCommand);
    addressForm.setCommandListener(this);
    // The connect form
    connectForm = new Form("Connecting");
    messageLabel = new StringItem(null, "Connecting...\nPlease wait.");
    connectForm.append(messageLabel);
    connectForm.addCommand(backCommand);
    connectForm.setCommandListener(this);
    // The display form
    displayForm = new Form("Server Reply");
    messageLabel = new StringItem(null, null);
    displayForm.append(messageLabel);
    displayForm.addCommand(backCommand);
    displayForm.setCommandListener(this);

    Hello all,
    I was wondering if someone found a solution to this..I would really appreciate it if u could post one...Thanks a lot..Cheerz

  • Has the ODI same installable for both Client & Server?

    Has the ODI same installable for both Client & Server?
    i.e. Team with multiple developers is concurrently working on ODI project. Repository is very much same. They just need the Designer Module in their desktop.
    Is there separate installable for development IDE for ODI (Designer Module) instead of complete ODI which may include the server also?
    Thanks In Advance
    priyadarshi.

    Hi ,
    You can install only the client in multiple machine if multiple user are going use/share the same repository ... and you should be having the same
    snps_login_work.xml
    snps_login_security.xml
    in all your client installations....so that you can have multiple users created and share the same repositroy ...
    hope this helps
    Thanks
    Ananda

  • HELP:USING CLIENT SERVER PROGRAM ON DIFF.MACHINES CONNECTED TO INTERNET?

    BELOW IS THE JAVA CODE FOR CLIENT & SERVER PROGRAM (TCP) USING SOCKET.
    I AM TRYING TO RUN CLIENT & SERVER PROGRAM ON 2 DIFFERENT MACHINES CONNECTED 2 INTERNET
    (1 RUNS SERVER.java & OTHER CLIENT.java).
    IS IT POSSIBLE WITH THE CODE WRITTEN BELOW?
    // Server.Java
    import java.net.*;
    import java.io.*;
    class Server {
    public static void main(String[] args) {
    boolean finished = false;
    try{
    ServerSocket listener = new ServerSocket(4444);
    while(!finished)
    {Socket to_client = listener.accept();
    OutputStream out = to_client.getOutputStream();
    PrintWriter pout = new PrintWriter(out, true);
    pout.println("Hello! this is server talking to you.");
    to_client.close();
    listener.close();
    }// end of try
    catch(Exception ie) {
    System.out.println(ie);
    //Client.Java
    import java.net.*;
    import java.io.*;
    class Client
    public static void main(String[] args)
    Socket client;
    String host="serverpcname";//host is assigned name of the server
    try
    {InetAddress adressen = InetAddress.getByName(host);
      client = new Socket(adressen,4444);
      BufferedReader scanf = new BufferedReader(new
      InputStreamReader(client.getInputStream()));
       String someString = scanf.readLine();
       System.out.println("From Server: "+someString);
      client.close();
    catch(Exception e)
    System.out.println(e);
    WHEN THE CODE IS EXECUTED(CLIENT.java ON 1 PC & SERVER.java on other) IT GIVES FOLLOWING EXCEPTIONS:
    java.net.UnknownHostException: serverpcname: serverpcname
    PLZ. GUIDE ME.
    THANKS IN ADVANCE.

    For a server to be accessible on the inetrnet it needs to have an externally visible IP address. For example, an address which starts with 192.168.1 is for internal use only can only be used by other machines on the same internal network. The server's firewall needs to allow the port you are using access and the client has to be able to lookup up the IP address either using the hosts file or via a DNS service. None of these things have anything to do with Java programming, so if you have any more questions I sugegst you try googling them or ask a forum which relates to these issues.
    The connection time out is due to the fact that there is no way to contact an inetrnal address over the inetrnet. The host unknwown means you haven't configured your PC to lookup that address. i.e. the host is unknown.

  • About the communication issues in the client-server program

    About the communication issues in the client-server program
    Hi, I have some questions about the communication issues in a java project, which is basically the client and server architecture. In brief, the client, written in java, can be deployed anywhere, and in the following part, assume it is in the LAN (Local Area Network) which is connnected to the internet through the firewall and/or proxy, and the server, written in
    java too, simply provides the listening service on a port in a remote machine. And assume the server is connected to the internet directly so that the scenario can be simple to focus on the core questions.
    My questions are as follows:
    1 About the relationship between the communication port and protocol
    Generally, protocols at the application level like HTTP, FTP have their own default port, e.g., HTTP is corresponding to 80,
    FTP is to 25. But it is NOT necessary for the web server to provide the HTTP listening service at port 80, right? E.g, Tomcat provides the HTTP listening service at 8080. So it means the default relationship between the application protocl and their port is some routine, which is not necessary to follow, right?
    2 Assume a LAN connected to the internet through a proxy, which only allows HTTP protocol, then questions are:
    2.1 Does the proxy recognize the HTTP request from the client by the port number (carried in the request string)? For example, when the server provides the HTTP listening service at 80, then the request from the client will include the port number 80, then the proxy will parse such info and decide if or not the request can be out.
    2.2 Does the proxy recognize the HTTP request from the client by protocol (carried in the request string)? For example, the protocol used in the communicatin should be included in the request, then the proxy can parse it to make the decision.
    3 In java programm, if using the HTTP protcol, then on the client: the corresponding API is java.net.URLConnection, right?
    If using the TCP protocol directly, then on the client:the corresponding API is java.net.Socket, right? In both cases, the server side use the same API, java.net.ServerSocket?
    Is it correct to say that the communication by Socket is faster than URLConnection?
    4 Take MSN messenger for example, which protocol does it use? Since proxy configure is only the possible option, so I guess generally the TCP protocol is used directly so that the better perfomrance can be achieved, right?
    5 Given 3 computers within the same LAN, can the client, proxy, server environment above be correctly simulated? If so, can
    you recommend me some typical proxy program so that I can install it to configure such an enviroment to perform some test?
    6 I guess there should be some software to find out which port number a given program/process is going through to connect to
    the remote machine, and which port number a given program/process is listening on? Also, what protocl is used in the given
    communication.
    7 Finally, regarding each of the above questions, it will be highly appreciated that if you can recommed some references,
    tutorials, books etc. In summary, what I care about is how to enable the java client behind the proxy and firewall to
    communicate with the remote server without problems, so if you know some good tutorials plz let me know and thx in advance!
    Finally, thanks for your attention so such long questions =).

    FTP is to 25. But it is NOT necessary for the web
    server to provide the HTTP listening service at port
    80, right? E.g, Tomcat provides the HTTP listening
    service at 8080. So it means the default relationship
    between the application protocl and their port is
    some routine, which is not necessary to follow,
    right?Not sure what you're saying here.
    There must be a server listening on some port. The client must know what port that is. If you open the connection using the Socket class, you'll explicitly specify the port. If you use some higher level class like URLConnection or something in the commons Net package, there's probably a default port that will be used if you don't explicitly specify another.
    There's no way for the client to know that the HTTP request will go to port 80 instead of port 8080. If you think the the client contacts the server without explicitly naming a port, and then asks the server "get me your HTTP server", and the port is determined from that, you're mistaken.
    Not sure if you're thinking that, but it sounded like you might be.
    2 Assume a LAN connected to the internet through
    a proxy, which only allows HTTP protocol, then
    questions are:
    2.1 Does the proxy recognize the HTTP request
    from the client by the port number (carried in the
    request string)? For example, when the server
    provides the HTTP listening service at 80, then the
    request from the client will include the port number
    80, then the proxy will parse such info and decide if
    or not the request can be out. I'm not sure, but I think most proxies and firewalls are configured by ports. I thought I'd heard of more sophisticated, higher-level ones that could understand the content to some degree, but I don't know anything about those.
    3 In java programm, if using the HTTP protcol,
    then on the client: the corresponding API is
    java.net.URLConnection, right?That's one way.
    You might want to look into this:
    http://jakarta.apache.org/commons/httpclient/
    If using the TCP protocol directly, then on the
    client:the corresponding API is java.net.Socket,
    right? In both cases, the server side use the same
    API, java.net.ServerSocket? A Java client will user Socket, and a Java server will use ServerSocket and Socket.
    Is it correct to say that the communication by Socket
    is faster than URLConnection?Probably not.

  • What is the best design pattern for this problem?

    No code to go with the question. I am trying to settle on the best design pattern for the problem before I code. I want to use an Object Oriented approach.
    I have included a basic UML diagram of what I was thinking so far. 
    Stated simply, I have three devices; Module, Wired Modem, and Wireless Modem.
    In the Device Under Test parent class, I have put the attributes that are variable from device to device, but common to all of them.
    In the child classes, I have put the attributes that are not variable to each copy of that device. The attributes are common across device types. I was planning to use controls in the class definition that have the data set to a default value, since it doesn't change for each serial number of that device. For example, a Module will always have a Device Type ID of 1. These values are used to query the database.
    An example query would be [DHR].[GetDeviceActiveVersions] '39288', 1, '4/26/2012 12:18:52 PM'
    The '1' is the device type ID, the 39288 is the serial number, and the return would be "A000" or "S002", for example.
    So, I would be pulling the Serial Number and Device Type ID from the Device Under Test parent and child, and passing them to the Database using a SQL string stored in the control of the Active Versions child class of Database.
    The overall idea is that the same data is used to send multiple queries to the database and receiving back various data that I then evaluate for pass of fail, and for date order.
    What I can't settle on is the approach. Should it be a Strategy pattern, A Chain of Command pattern, a Decorator pattern or something else. 
    Ideas?

    elrathia wrote:
    Hi Ben,
    I haven't much idea of how override works and when you would use it and why. I'm the newest of the new here. 
    Good. At least you will not be smaking with a OPPer dOOPer hammer if I make some gramatical mistake.
    You may want to look at this thread in the BreakPoint where i trie to help Cory get a handle on Dynamic Dispatching with an example of two classes that inherit from a common parent and invoke Over-ride VIs to do the same thing but with wildly varying results.
    The example uses a Class of "Numeric"  and a sibling class "Text" and the both implement an Add method.
    It is dirt simple and Cory did a decent job of explaining it.
    It just be the motivation you are looking for.
    have fun!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • JMS architecture question for fat client/server.

    Hi. Is JMS suitable for fat client-server architecture where a certain number of fat client applications (like a few hundreds) open connections directly to the JMS provider? Is it going to have scalability problem when the number of connections grow?

    Depending on your JMS provider, this may be a very suitable architecture. The Sun MQ JMS Cluster was architected exactly for this problem. If the number of connections onto a single broker becomes too much of a burden for this broker, it can be put into an MQ cluster and share the number of connections. Of course, the number of connections a broker can handle will be totally dependent on the resources available to it. OS, CPU, memory, other applications running on the same machine, etc....
    TE

Maybe you are looking for

  • Windows not remembering settings in MacBook Pro 15"

    hey all, I have a MacBook Pro 15" released in 2008. I have dual booting set up between Mac OS X.5.6 and Windows XP. I have what I'd consider a unique problem but may be someone else out there has had similar issues. Every time I launch into Windows,

  • TomCat Server 5.0

    dear friends, i am very new to java technology. now i downloaded j2ee in windows but it is not working. some people told me to install tomcat server as webserver. so plz tell me how can i download tomcat server. plz tell me in deatail the process. be

  • Hi, how do i fix it ? Its only on YT i have 27" screen

    Firefox 17.0.1 Windows 7 Adobe Flash Player 11.5.502.110

  • Crash when using text tool.

    Hi, my Photo shop CS3 always freezes when I'm trying to use the text tool. I already deactivated all but the default fonts and I looked for damaged fonts. Now I don't know what to do...

  • Signing in on "Your Account"

    When I click on "sign in" in Elements 10, I complete the short form, and am told I am recognized by Adobe. The next screen is "Your Account," and when I complete it, I am told an "error" has occured, and the "changes are not saved." Am I doing someth