Client/socket design problem

i am having a client /server design where in the client talks to the server via sockets and i am putting code ofboth the client as well as server in the different loop while(true) at respective ends so that they can talk as long as they would like to but the client hangs upon receiving response from server . please guide me what to do.
the client side code is
while(true)
temp1=clientbfr.readLine();
//System.out.println(temp);
if(temp1==null)
else if(temp1.indexOf("Login-")==0)
System.out.println(temp1);
temp1="";
the server side code is the same and that works fine. again if a second clinet requests a socket to the server then that client also hangs. so i think i am not able to view the picture properly. please guide me.

Is the server reading before writing? If so, the client will hang until it has sent something for the server to reply to.

Similar Messages

  • An rmi client server design problem

    I am implementng a networked cards game in java using rmi . The server keeps track of the turn of the players and activates ther clients(on an applet) whose turn it is to play .
    Both client and server call each others methods.
    Prblem one :
    Right now if a a client disconnects , a process run through all the clients active and gets a remote exception on the server and removes ALL the 4 players i nthat particulat group. If I want to save the state and allow any player to contuniue from there , how will I do it?
    Problem 2:
    How do I keep track of the time a client takes to play.
    If he takes longer than say 5 mintes , I should disconnect him.

    There seem to be two issues at stake: <b>catching the remote exception</b> and <b>multithreading</b> your application on the server.
    When a client disconnects "suddenly" (without logging off via remote method call to alert server), the remote method call by the server to all <i>n</i> players triggers a remote exception that must be caught and dealt with accordingly (do I understand that it is causing the application to exit at present?) When caught, you must identify which player is "gone" and remove that client from the pool of client objects.
    Right now, it sounds as if the app is NOT multithreaded. You can create a low-priority thread that looks at a time variable for each player to determine its last moment of play. This means every successful remote call from client-server or vice-versa will update that client's 'lastplayed' variable with (long) System.currentTimeMillis() for example.

  • Servlet Server Socket Communication problem

    Hi
    Iam having this problem ...when I read data in server line by line it works but when I try to read byte by byte server hangs. This is my code
    BufferedReader in = new BufferedReader(
    new InputStreamReader(
    clientSocket.getInputStream()));
    //it works fine when i do
    String strLine = in.readLine();
    //but hangs when I do like this
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int r = in.read();
    while(r != -1)
    baos.write(r);
    r = in.read();
    I am sending data from the client socket as
    out = new PrintWriter(addArtSocket.getOutputStream(), true);
    I just do out.println to send data.
    Is there something wrong that I am doing?
    Thanks
    vinitha

    hi,
    basically, I suggest that you have the communication
    channel in the same type between two ends. For example,
    if you decide to connect two side byt Stream, you just
    apply your code in the sort of Stream for I/O.
    If you decide to connect two sides by Reader/Writer, you
    apply your code in the sort of Reader/Writer for I/O.
    Don't mix them up. Although I don't know what may
    happen. For example, you want to pass an Object
    between two ends, you could use ObjectInputStream/
    ObjectOutputStream pair on two sides. Don't put
    ObjectInputStream in one side and talk to one sied
    which write data by other OutputStream filteer but
    not ObjectOutputStream .
    You may find something interesting.
    good luck,
    Alfred Wu

  • Client socket binding to the same local/remote addresses

    Hi all,
    My Java program binds client socket to local address, local port, remote address and remote port. after that from different thread the program creates new socket and bind it to the same address as the first one. The question is: is there possibility that the second socket will be copy as the first one (with the same input/output streams) so that two threads in fact use the same TCP connection.
    (Operating system is HP).
    Thank you,
    Kate

    I have no need to store streams, my problem that each connection has it's own messages numbers(the application implements some protocol over TCP). so if a message number 1 was sent by some connection, and when different thread wants to send a message to the same remote host, it tries to pick up existing connection, but because of a bug creates the new one, which sends the message with number 1 also. And I see that there are situation whent the first thread receives response to the message number 1 althougth it was response to the message number 1 that the second thread has sent. So my question is if there is any possibility of this absurd situation?

  • Client Server Thread Problems

    When I invoke the method getNextJob() in my Client.
    This sends a this message (CLNT::GETNEXTJOB) to the server which then triggers the Server to invoke the corresponding method and send back another message. (Which as far as I know it does).
    My problem is this, when I run the getNextJob() method a thread is supposed to be created and ran in parallel which listens for the Servers reply and unfortunately this thread keeps telling me that its get a NullPointerException (specifically at my Socket connection clientSocket). If I uncomment out this.openConnection(); within my run() method it works BUT I get no response from my server even though it is telling me it has sent a message.
    I hope you can help.
    OUTPUTTED TEXT
    CLIENT:  Building GUI
    CLIENT:  Get Next Job Invoked
    CLIENT:  Opening Connection
    CLIENT:  Socket is now OPEN
    CLIENT:  Listerner Loaded
    Exception in thread "Thread-2" java.lang.NullPointerException
    CLIENT ->CLNT::GETNEXTJOB JAVA CODE
    package Client;
    import java.net.*;
    import java.io.*;
    public class Kernel implements Runnable {
        //Socket Variables & Streams
        Socket clientSocket;
        //variables
        private boolean msgReceived = true;
        private String faultNumber;
        //listening thread
        public void run()  {
                String serverMessage = "ERROR: run";
                System.out.println("CLIENT:  Listerner Loaded");
                //builds listener
                try {
                     //this.openConnection();
                    //opens socket connection
                     BufferedReader in = new BufferedReader(
                                                    new InputStreamReader(
                                                    this.clientSocket.getInputStream()));
                     BufferedReader stdIn = new BufferedReader(
                                                    new InputStreamReader(
                                                    System.in));
                    while((stdIn.readLine()) != null) {
                        System.out.println("CLIENT:  Listener Received Line = " + stdIn.readLine());
                        serverMessage = stdIn.readLine();
                   System.out.println(in.readLine());
                    msgReceived = false;
                    in.close();
                    stdIn.close();
                } catch(IOException e) {System.err.println("Error Details:" + e);}
                //sets current Tail to new value returned
                this.setCurrentTail(serverMessage);
       private void openConnection() throws IOException{
            try {
                System.out.println("CLIENT:  Opening Connection");
                this.clientSocket = new Socket("localhost", 4444);
            } catch (UnknownHostException e) {
                System.err.println("CLIENT:  Host not found");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("CLIENT:  Couldn't get I/O for the connection to: Brenda.");
                System.exit(1);
        public String getNextJob()
            System.out.println("CLIENT:  Get Next Job Invoked");
            try{
                //opens socket connection
                this.openConnection();
                //waits for the socket to open
                System.out.println("CLIENT:  Socket is now OPEN");
                //invokes Listener
                (new Thread(new Kernel())).start();
                //sends a message
                this.sendMessage("CLNT::GETNEXTJOB");
                //waits for a reply from the server
                //while(msgReceived){}
                //closes socket connection
                //this.closeConnection();
            }catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: taranis.");
                System.exit(1);
            return this.getCurrentTail();
        private void setCurrentTail(String tail) {
            this.faultNumber = tail;
        private String getCurrentTail() {
            return this.faultNumber;
        private void closeConnection()
            try{
                clientSocket.close();
                System.out.println("CLIENT:  Connection Closed");
            }catch (IOException e) {e.printStackTrace();}
        private void sendMessage(String strMessage){
                try{
                    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                    out.println(strMessage);
                    System.out.println("CLIENT ->" + strMessage);
                    //Closes output stream.
                    out.close();
                }catch(IOException e){System.err.println(e);}
    }Edited by: DaveyB on Sep 2, 2009 3:19 PM

    I have made some modifications based on the above information but I have hit another brick wall.
    The below code returns this to the output pane:
    run:
    CLIENT:  Building GUI
    CLIENT:  Get Next Job Invoked
    Never Reached Statement Within getNext StartValue
    CLIENT:  Listerner Loaded
    CLIENT:  Opening Connection
    CLIENT ->CLNT::GETNEXTJOB
    STATEMENT NEVER REACHED
    null
    ErrorWhat you can see is the CLIENT sets up the connection and invokes the Listener thread (run). When this is ran it hits the while loop and even when a non null value is returned via the .ReadLine() as shown via the second value in the output pane {'null', 'Error'} it doesn't exit the loop.
    Any ideas why this would be.
    package webtoolclient;
    import java.net.*;
    import java.io.*;
    public class Kernel implements Runnable {
        //Socket Variables & Streams
        Socket clientSocket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        //variables
        private String faultNumber = "StartValue";
        private boolean isListenerLoaded = false;
        //listening thread
        public void run()  {
                //String serverMessage = "ERROR: run";
                System.err.println("CLIENT:  Listerner Loaded");
                //builds listener
                try {
                    //opens socket connection
                    this.openConnection();
                    //sends a message
                    this.sendMessage("CLNT::GETNEXTJOB");
                    //creates inputstreams
                     in = new BufferedReader(
                                                    new InputStreamReader(
                                                    this.clientSocket.getInputStream()));
                    String line = null; // in.readLine();
                    while((line = in.readLine()) != null){
                        System.out.println(line);
                    System.out.println("STATEMENT NEVER REACHED WITHIN THREAD line = " + line);
                    this.setCurrentTail(line);
                    this.isListenerLoaded = true;
                    //in.close();
                    //stdIn.close();
                    //this.closeConnection();
                } catch(IOException e) {System.err.println("Error In run: " + e);}
                //sets current Tail to new value returned
                //this.setCurrentTail(line);
       private void openConnection() throws IOException{
            try {
                System.err.println("CLIENT:  Opening Connection");
                this.clientSocket = new Socket("localhost", 4444);
            } catch (UnknownHostException e) {
                System.err.println("CLIENT:  Host not found");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("CLIENT:  Couldn't get I/O for the connection to: Brenda.");
                System.exit(1);
        public String getNextJob()
            System.err.println("CLIENT:  Get Next Job Invoked");
            //try{
                //opens socket connection
                //this.openConnection();
                //waits for the socket to open
               //System.err.println("CLIENT:  Socket is now OPEN");
                //invokes Listener
                new Thread(this).start();
                //ensures Listerner is open before message is sent.
                while(this.isListenerLoaded){}
                //waits for a reply from the server
                //while(this.getCurrentTail().equals("StartValue")){}
                System.err.println("Never Reached Statement Within getNext " + this.getCurrentTail());
                //closes socket connection
                //this.closeConnection();
                return this.getCurrentTail();
            /*}catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: taranis.");
                System.exit(1);
           //return this.getCurrentTail();
        private void setCurrentTail(String tail) {
            this.faultNumber = tail;
        private String getCurrentTail() {
            return this.faultNumber;
        private void closeConnection()
            try{
                clientSocket.close();
                System.err.println("CLIENT:  Connection Closed");
            }catch (IOException e) {e.printStackTrace();}
        private void sendMessage(String strMessage){
               try{
                    out = new PrintWriter(clientSocket.getOutputStream(), true);
                    out.println(strMessage);
                    System.err.println("CLIENT ->" + strMessage);
                    //Closes output stream.
                    //out.close();
                }catch(IOException e){System.err.println(e);}
    }

  • Tracking data on Client Socket

    Hey, help me to figure this out, i have condition like this
    Client request via browser and then the request go through RMI Server, RMI Server create Socket,which is connected to dummy machine, RMI Server send the request to the dummy machine to be proceed, after the dummy machine proceed the request it will sending to RMI Server, and RMI Server forwarded to the client via AppServer...
    My problem are, if i send the request with many client on the same time, i got the data but the data is not what i wanted means that my data go through another client, how to solve this?
    can i create thread on my socket which is connected to the dummy machine (If i use ServerSocket i can thread this,but i'm not using serverSocket) the dummy machine only can connected via socket(client socket type)
    i figure this problem like this, why i got the different response from what i requested,cos if many client request in the same time, my socket not handle FIFO,correct me if i'm wrong? i want to create process like this, if the socket is using, the another client must be wait, is there any method that i can use for tracking the data on the socket?
    I think about another solution, how about creating threads on my RMI at receiving and sending method?
    If there any solution please help me figure this out...
    Thanks....

    There should be a simple applet that continuously checks your account and tells you how much bandwidth usage your computer/device, and all other computers/devices have used so far during your billing period, individually and total for the device/account.
    I consider this situation to be a SERIOUS lacking/missing feature that should have been created BEFORE 4G service and the MiFi 4510L were offered.  The FCC should REQUIRE all wireless providers to provide a VERY simple, automatic method of continuously diplaying bandwidth usage for each account, and for each device using the account.  This is NOT rocket science by any means.
    Steve

  • BindException on client Socket?

    When opening many client sockets under win2k, I am getting BindExceptions. This is without specifying any particular local port. The total number of simultaneous sockets open is only around 14 or 15, but thousands are being opened in a 1-2 minute period.
    A BindException with a Socket(host, port) call seems counter-intuitive. I would assume that the OS is suppose to open it using an unused local port.
    From my testing, it appears that the java.net.Socket() class only obtains local ports from the 1024-5000 port range. It seems to go through the range and wrap around a couple of times before the BindExceptions pop up.
    Note that this appears to be the correct port range to allocate from based on various documentation, even though an equivalent program written in C does not seem to limit itself to that range (and does not exhibit the binding problem).
    If I set the windows registry entry of MaxUserPort to a higher number, it takes longer for the BindException to occur since it has more ports to utilize. However, the problem doesn't go away.
    Has anyone else seen this issue and come up with a solution? (Looping on the socket creation does not seem to be a very good long term solution)
    Attached is a simple program which demonstrates the issue by making multiple HEAD requests to a webserver.
    SockTest.java:
    public class SockTest
         public static void main(java.lang.String[] args)
              int i;
              for (i = 0; i < 14; i++)
                   SockTestThread thread = new SockTestThread();
                   thread.start();
    }SockTestThread.java:
    public class SockTestThread extends java.lang.Thread
         private void runTransaction(java.lang.String hostname, int port)
              try
                   java.net.Socket sock;
                   java.io.PrintStream out;
                   java.io.InputStream in;
                   java.lang.String request = "HEAD / HTTP/1.0\n\n";
                   byte[] response = new byte[4096];
                   sock = new java.net.Socket(hostname, port);
                   out = new java.io.PrintStream(sock.getOutputStream());
                   in = sock.getInputStream();
                   java.lang.System.out.println("Making request from local port " + sock.getLocalPort());
                   out.print(request);
                   out.flush();
                   in.read(response);
                   sock.close();
              catch (java.lang.Exception exception)
                   java.lang.System.out.println(exception);
         public void run()
              int i;
              for (i = 0; i < 1000; i++)
                   this.runTransaction("webserver", 80);
              java.lang.System.out.println("Finished thread");

    There is only ever 14 sockets open at any one time. You will notice that the 1000 connections are done serially for each of the 14 threads. So, a socket is opened and closed (released) after each connection.
    I'm not sure how a socket pool could be used/implemented here to help this. Also, up until the recent JDK1.4 release, there didn't appear to be a way to reuse a client socket. As far as I can tell, one can only create new sockets. Also, JDK 1.4 is not currently an option for me.
    While this sample program just connects to a single web server to demonstrate the issue, the real application will be connecting to many different servers (web and others) and needs to be able to process the information and move on after each connection.

  • Closing a client socket

    I have a chat application.
    My server has a serversocket that listens on a port various client sockets.
    the server is multithreaded, a thread per connected client.
    the client application uses a thread to listen for messages from server.
    the run method in the client is a
    while(messageFromServer.equals("OVER"))
    Also, the client has a GUI with a menu with 2 menu items:
    Connect
    Disconnect
    on Connect, i create the socket, i create the 2 streams(in and out)
    and write something to the server and start the thread for reading from the socket.
    my problem:
    I can't disconnect without blocking the application.
    Voila the code that blocks it:
    public void terminate_connection()
    write_on_socket("OVER");
    try
    in.close();
    out.flush();
    out.close();
    terminal.close();
    catch(IOException ioe)
    System.out.println("eroare"+ioe);
    in=the inputstream on the socket
    out=the outputstream on the socket
    terminal= the socket
    I have tried to debug with System.out.println(error)
    and it seems to stop execution when i try to close the inputstream
    in.close();
    Can someone please help me by telling me where I am wrong
    or showing me some good code of disconnecting a socket and to notify also the peer socket that the socket is terminating(dying).
    Thanx in advance.
    Gabi

    While I'm not sure why your code is blocking...I put together a test chat program to try and help...maybe you can see something that you are doing differently...the following is 'ClientServer.java' compile and run 'ClientServer'.
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    class Server extends Thread{
         private ArrayList clients;
         public void run(){
              clients = new ArrayList();
              try{
                   ServerSocket ss = new ServerSocket(8181);
                   while(true){
                        try{
                             ServerThread th = new ServerThread( ss.accept(), this );
                             clients.add( th );
                             th.start();
                        }catch(Exception ex2){
                             ex2.printStackTrace();
              }catch(Exception ex){
                   ex.printStackTrace();
         public void sendToAll(String text){
              Iterator iter = clients.iterator();
              while( iter.hasNext() ){
                   ServerThread st = (ServerThread)iter.next();
                   try{
                        st.send( text );
                   }catch(Exception ex){
                        iter.remove();
    class ServerThread extends Thread{
         private Socket s;
         private PrintStream out;
         private BufferedReader in;
         private Server server;
         public ServerThread(Socket s, Server server)throws IOException{
              this.server = server;
              this.s = s;
              this.in = new BufferedReader( new InputStreamReader( s.getInputStream() ) );
              this.out = new PrintStream( s.getOutputStream() );
         public void run(){
              try{
                   String text = "";
                   do{
                        text = in.readLine();
                        server.sendToAll( text );
                   }while( !text.equals( "QUIT" ) );
                   in.close();
                   s.close();
              }catch(Exception ex){
                   ex.printStackTrace();
         public void send(String st){
              out.println(st);
    class Client extends JFrame{
         Socket s;
         PrintStream out;
         BufferedReader in;
         private JTextArea messageArea;
         private JTextField textField;
         public Client(){
              super("Client Window");
              JPanel buttonPanel = new JPanel();
              JButton connect = new JButton("Connect");
              connect.addActionListener( new ActionListener(){
                   public void actionPerformed( ActionEvent evt ){
                        connect();
              buttonPanel.add( connect );
              JButton disconnect = new JButton("Disconnect");
              disconnect.addActionListener( new ActionListener(){
                   public void actionPerformed( ActionEvent evt ){
                        disconnect();
              buttonPanel.add( disconnect );
              getContentPane().add(BorderLayout.SOUTH, buttonPanel);
              messageArea = new JTextArea();
              messageArea.setEditable( false );
              getContentPane().add( messageArea);
              JPanel textPanel = new JPanel();
              textPanel.setLayout(new BorderLayout());
              ActionListener sendAction = new ActionListener(){
                   public void actionPerformed( ActionEvent evt ){
                        if( ! "".equals( textField.getText() ) ){
                             out.println( textField.getText() );
                             textField.setText("");
              textField = new JTextField();
              textField.addActionListener( sendAction );
              textPanel.add( textField );
              JButton sendButton = new JButton("send");
              sendButton.addActionListener( sendAction );
              textPanel.add( BorderLayout.EAST, sendButton );
              getContentPane().add(BorderLayout.NORTH, textPanel);
              setSize(200, 300);
              setVisible(true);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public synchronized void connect(){
              if( s == null ){
                   try{
                        s = new Socket("localhost", 8181);
                        out = new PrintStream( s.getOutputStream() );
                        in = new BufferedReader( new InputStreamReader( s.getInputStream() ) );
                        (new ClientThread( this )).start();
                        out.println("connected");
                   }catch(Exception ex){
                        ex.printStackTrace();
         public synchronized void disconnect(){
              if( s != null ){
                   try{
                        out.println("QUIT");
                        out.close();
                        s.close();
                        s = null;
                   }catch(Exception ex){
                        ex.printStackTrace();
         public void addMessage(String st ){
              messageArea.append( st + "\n");
         public BufferedReader getReader(){
              return in;
    class ClientThread extends Thread{
         private Client c;
         public ClientThread( Client c ){
              this.c = c;
         public void run(){
              BufferedReader reader = c.getReader();
              try{
                   while(true){
                        c.addMessage( reader.readLine() );
              }catch(Exception ex){
                   ex.printStackTrace();
    public class ClientServer{
         public static void main(String[] args){
              (new Server()).start();
              new Client();
    }

  • Server/Client Socket Connection

    Hi, I am trying to program a simple server/client socket connection program, the main function is to send and receive objects between them. I somehow went wrong and the connection between them keeps terminating right after establishing connection. Is there anything I can do to resolve this?
    This is gonnna be kinda long post.. sorry. These are the code that starts and ends the socket connection. I'm kinda desperate for this to work.. so thanks in advance.
    appinterface.java:
    //Set up server to receive communications; process connections. 1x.
         public void runServer () {
              try {
                   //Create a ServerSocket
                   server = new ServerSocket(12345, 100);
                   try {
                             waitForSockConnection();     //Wait for a connection.
                             getSockStreams();               //Get input & output streams.
                             establishDbConnection();     //Open up connection to DB.
                   finally {
                             closeSockConnection(); //Close connection.
              //Process problems with I/O
              catch(IOException ioException) {
                   displayMessage("I/O Error: " + ioException);
                   runServer();
         //Wait for connection to arrive, then display connection info
         private void waitForSockConnection() throws IOException {
              displayMessage("Waiting for connection");
              connection = server.accept(); //Allow server to accept connection.
              displayMessage("Connection received from: " + connection.getInetAddress().getHostName());
         //Get streams to send and receive data.
         private void getSockStreams() throws IOException {
              //Set up output streams for objects
              ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
              output.flush(); //Flush output buffer to send header information.
              //Set up input stream for objects.
              ObjectInputStream input = new ObjectInputStream(connection.getInputStream());
              try {
              classHolderServer holderObj = new classHolderServer();
              holderObj = (classHolderServer)input.readObject();
              processSockConnection(holderObj);
              displayMessage("Got I/O Streams");
              //Catch problems reading from client
              catch (ClassNotFoundException classNotFoundException) {
                             displayMessage("Unknown object type received");
         //Process connection with client.
         private void processSockConnection(classHolderServer holderObj) throws IOException {
              //sendMessage("Connection Successful");
                        //True is query, and false is auth.
                        if(holderObj.type1==true)
                             processDbStatement(holderObj.type2, holderObj.sqlquery);
                        else {
                             authCheck(holderObj.userName, holderObj.passWord);
                             if(!authCheck)
                             closeDbConnection();
         //Send messages to client.
         private void sendMessage(String message) {
              // Send message to client
              try {
                   ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
                   output.flush();
                   output.writeObject(message);
                   output.flush();
                   displayMessage("Message Sent:" + message);
              catch (IOException ioException) {
                   displayMessage("\nError Sending Message: " + message);
         //Send object to client
         private void sendObject(Object holderObj) {
                   // Send object to client
                   try {
                        ObjectOutputStream output = new ObjectOutputStream(connection.getOutputStream());
                        output.writeObject(holderObj);
                        output.flush();
                        displayMessage("\nObject sent");
                   //Process problems sending object
                   catch (IOException ioException) {
                        displayMessage("\nError writing object");
         //Close streams and socket.
         private void closeSockConnection() {
                   displayMessage("Terminating connection");
                   try {
                        //output.close();
                        //input.close();
                        connection.close();
                        closeDbConnection();
                        this.userName = null;
                        this.passWord = null;
                        this.receiverId = 0;
                        this.authCheck = false;
                   catch (IOException ioException) {
                        displayMessage("I/O Error: " + ioException);
              }Client:
    private void runClient() {
              //Connect to sever and process messages from server.
              try{
                   connectToServer();
                   getStreams();
                   processConnection();
              //Server closed connection.
              catch(EOFException eofException) {
                   //displayMessage"Client Terminated Connection");
              //Process problems communicating with server.
              catch (IOException ioException) {
                   //displayMessage"Communication Problem");
              finally {
                   closeConnection();
         //Connect to server
         private void connectToServer() throws IOException {
              //displayMessage("Attempting connection\n");
              //Create Socket to make connection to sever.
              client = new Socket(InetAddress.getByName(chatServer), 12345);
              //Display connection information
              //displayMessage("Connected to: " + client.getInetAddress().getHostName());
         //Get streams to send and receive data.
         private void getStreams() throws IOException {
              //Set up output stream for objects.
              ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
              output.flush(); //Flush outout buffer to send header information.
              //Set up input stream for objects.
              ObjectInputStream input = new ObjectInputStream(client.getInputStream());
              //displayMessage("\nGot I/O streams\n");
         //Close socket connection.
         private void closeConnection() {
              //displayMessage("\nClosing connection");
              try {
                   ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
                   output.close();
                   ObjectInputStream input = new ObjectInputStream(client.getInputStream());
                   input.close();
                   client.close();
                   authCheck=false;
              catch(IOException ioException) {
                   ioException.printStackTrace();
         //Send data to server.
         private void sendObject(classHolderClient queryObj) {
              try {
                   output.writeObject(queryObj);
                   output.flush();
                   //displayMessage("Please wait..");
              //Process problems sending object.
              catch (IOException ioException) {
                   //displayMessage("\nError writing object");
         //Process connection with server.
         private void processConnection() throws IOException {
              try{
                   classHolderClient holderObj = new classHolderClient();
                   holderObj = (classHolderClient)input.readObject();
                   if(holderObj.type2==2) {
                             this.authCheck=holderObj.authCheck;
                             this.userName=holderObj.userName;
                             this.passWord=holderObj.passWord;
              catch(ClassNotFoundException classNotFoundException) {
                   //displayMessage(classNotFoundException);
              }

    private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());Like this? But this will cause an error asking me to catch an exception:
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\client.java:41: unreported exception java.io.IOException; must be caught or declared to be thrown
            private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
                                                                                             ^
    C:\Documents and Settings\Moon\My Documents\Navi Projects\School\OOPJ Project\Prototype\GPS-Lite v2 Alpha Debugger\client.java:41: unreported exception java.io.IOException; must be caught or declared to be thrown
            private ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
                                                ^
    2 errors

  • Design problem with Swing

    Hi all. I've run into some design problems when trying to create a Swing app.
    I've got a non-graphical class that emulates a power supply unit. Let's call it PSUnit. I have to create a GUI for PSUnit.
    Every class designed to build a full GUI app uses PSUnit in some way (changes its voltage, displays voltage, turns it on, turns it off, etc.)
    Here's the catch. Suppose I've got a class:
    public class BuildingBlock extends JPanel {
         // code includes a JTextBox displaying
         // the current PSUnit voltage.
    }another class is created for setting the voltage:
    public class AnotherBlock extends JPanel {
         // this class contains a JSpinner and
         // a button that retrieves the JSpinner value
         // and sets it as the current voltage of
         // PSUnit
    }When the button in AnotherBlock is clicked, I must notify the BuildingBlock class that a PSUnit has changed its state so it can update it's values and display the correct data.
    I've tried to do this a few times but failed miserably, so I'm hoping you guys could help me out.
    Please note that both of the above classes have some additional code and it's not very pleasant to make one class an inner class of another. I should be able to create a "standalone" classes which, combined together, form a GUI for PSUnit.
    Thanks.

    Yes this is a common problem that many of us have when building UIs
    Here's the question: In this instance, are these two classes really independant? Could they stand alone? Often when building a GUI, it's not even that easy to answer that question, but these leads to the two ways you can solve this
    #1. Make them independent, and use listeners either using Observable / Observer or creating your own custom listeners. The advantage of this is smaller classes and more independence. The disadvantage is it's generally more complicated, especially at the design stage
    #2 (what I'd probably recommend). Make 1 GUI class "MyPSFrame", then declare your panel classes as inner classes within that class. This way, everything goes into one spot, and everything is shareable. This also makes sense if you can't have 1 of the panels without the other.

  • Design problem about repreatable entity relationships

    Hi all!
    As I design the data model (let's name it the ERD, no matter the name is quite unfashonable), I have found almost identical structures of entities and relationships between them, but playing completely different roles in the semantics of the model.
    It obviously makes no sense to implement all such entities separately as the Entity EJB as they are to share most of the fields and methods, but I found no "handsome" solution when trying to implement them as sets of classes and interfaces forming "the abstract EJBs", and then by putting the conrete classes and complementary interfaces at the final packages to create "concrete EJBs". The problem was about types returned by the createXXX and findXXX methods, because they had to return the "abstract" EJBs but the EJB programming contract forces them to return the "concrete" ones, that are unknown to me when defining the "abstract ones". So it cancels the sense for creating them this way. It was also unclear how to operate the relationships in such model.
    The idea was:
    1. I define BaseSthLocalHome extends EJBLocalHome
    2. I define BaseSthLocal extends EJBLocalObject
    3. I define BaseSthBean implements EntityBean
    ... this way I have the "abstract bean", and then I can create many:
    SthOneLocalHome extends BaseSthLocalHome,
    SthOneLocal extends BaseSthLocal,
    SthOneBean extends BaseSthBean ... to have the first "concrete" EJB,
    SthTwoLocalHome extends BaseSthLocalHome... and so on to create the second, third and all the next "concrete" EJBs.
    Anyway, it did not work fine as I defined createXXX and findXXX methods at the BaseSthLocalHome interface - it made sense, because those methods did not depend on the other entities.
    Has anyone some idea of how to solve the design problem? Currently we are at very beginning of the project, so we have some "case study" time, and I would appreciate any solution: redesign of the data model, extraction of new EJB modules or any use of the objective inheritance.
    Thanks in advance!
    Marcin Gawlik

    Again me - I now it is a bad idea to reply for own messages, but I have just checked a new idea:
    The problem was about re-using the same components in different roles. I tried to do that by creating subclasses of the EJB classes, but it did not work. So I tried to define multiple entity EJBs that have the same class.
    Considering the given example, it would look:
    1. public interface BaseSthLocalHome extends EJBLocalHome
    2. public interface BaseSthLocal extends EJBLocalObject
    3. public abstract class BaseSthBean implements EntityBean
    ... then I created the deployment descriptor that deploys this pack of class and interfaces as three separate CMP Entity Beans:
    1. deploy BaseSthBean as the SthOne CMP entity EJB
    2. deploy BaseSthBean as the SthTwo CMP entity EJB
    3. ... and so one
    The question is: IS THERE ANY CONTRA FOR THIS WAY OF DEPLOYING EJBS? Is there any reason for not to use the same class and its complementary interfaces many times to create many separate enity EJBs working within the same EJB module?
    Thanks in advance!
    Gaw

  • Design problem/Ex​ercise Book

    Hi Everyone,
                       I am new to Labview. I just started with Labview 2011 student edition and I am following Bishop's book. But I also want a tutorial book with lots of design problems and exercises to get my skills. I am a postdoc in purdue and I started learning LabViews just because I want to learn (I am facinated by the G programming. I use it in my instrument but the departmental engineers wrote it and I want to have the same type of skills. I am also intending to become CLD). Can anyone suggest me any book or any website where I can find exercises and design problem? Thank you everyone.
    Cheers!
    Solved!
    Go to Solution.

    Ekram wrote:
    Hi Everyone,
                       I am ...Can anyone suggest me any book or any website where I can find exercises and design problem? Thank you everyone.
    Cheers!
    You found it!
    Get involved answering questions (gird up your loins) and let others hammer you into submision. Don't fall into the trap of writing code and posting VIs on demand, but rather post images of how you want to solve the posted question and let others feedback.
    Have fun!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Design problem with JScrollPane

    First, I have problems with english. I hope u understand without problems that Im trying to say here. Sorry about that.
    Mi problem is whit a JScrollPane. I want to put an image whit a predefined size for draw inside it. I dont have any information about it, just the size. I want to put it in a JPane. The best choice is use the JPane area. The problem is that I want to use a JScrollPane because the image is bigger that the visualization area.
    Im unable to put a Canvas in the ScrollPane, or a JPane whit a predefined size or an image whit a predefined size. Im sure that is a design problem. Somebody can tell me something I can start whit? What do u think is better choice to put inside a JScrollPane?
    I dont send any source code because I dont have anything else that is show in the example.
    Gracias.

    import java.awt.*;
    import javax.swing.*;
    import java.net.URL;
    public class Test extends JFrame {
      String url = "http://www.sandbox-usa.com/images/product_images/2piece_16.gif";
      public Test() {
    //    System.getProperties().put( "proxySet", "true" );  // uncomment if you have proxy
    //    System.getProperties().put( "proxyHost", "myproxy.mydomain.com" ); // Your proxyname/IP
    //    System.getProperties().put( "proxyPort", "80"); // Sometimes 8080   
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
        Container content = getContentPane();
        try {
          Image i = Toolkit.getDefaultToolkit().getImage(new URL(url));
          JLabel jl = new JLabel(new ImageIcon(i));
          content.add(new JScrollPane(jl), BorderLayout.CENTER);
          setSize(200, 200);   
          setVisible(true); 
        } catch (Exception e) { e.printStackTrace(); }
      public static void main(String[] args) { new Test(); }
    }

  • Design problem: Central MessagePool in WebDynpro App.

    Hi people,
    I have a design problem in my webdynpro application:
    I'm designing an application with different DC's. The architecture of the application is similar to the architecture described in the document "Web Dynpro Component
    Interface Defintions in Practice SAP NetWeaver ’04s": One root DC which manages the differnt child DC's, which contain the application content.
    Now I want to have a central MessagePool. Certain Messages in the child DCs are the same, and I don't want to have multiple MessagePool-entries for the same Message (each child DC has to define its own messages).  I can't  use the root DC as central MessagePool, because the Child DCs havn't access to the root-DC.
    Any idea, how to define and use a central MessagePool?
    Regards,
    Thomas

    Hi Thomas,
    Instead of the architecture what you are thinking try the architecture explained in the following link:
    <a href="https://www.sdn.sap.comhttp://www.sdn.sap.comhttp://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/f4d79e59-0601-0010-0689-89670315bc6b">link</a>
    Dont forget to award points on helping answers
    Regards
    sid

  • Design problem: RS232 communication

    Hi,
    I have a design problem for communication with a device via RS232. Since I'm normally a C++ programmer I might just look at the problem from a wrong angle and hope for some hints how to do it in LabVIEW.
    The scenario:
    A device is communicating with the PC via RS232. The device permanently sends data packets. At the same time, commands can be sent to the device and it returns replies. Data packets and reply packets are arbitrarily mixed, i.e. after sending a command there could be a couple of date packets before the reply comes back but the packets can be distinguished by an identifier.
    At least one, ideally several VIs should communicate with the device. Commands should be sent by pressing buttons and the incoming data should be parsed (the packets contain mutliple data streams) and shown on graphs or saved to files.
    My initial idea:
    Coming from C++ I wanted to build a class for the communication that permanently reads the incoming data and splits it to reply and data packets. This class would then have a function to send out a command and would return the reply or a timeout and it would be possible to register and unregister listeners (I wanted to use queues for this) for the various data streams.
    The problems I ran into:
    There were a couple but the two most pressing problems were: how could I communicate with the constantly running sample VI (e.g. to stop sampling) and how could I propagate changes to the class to it (e.g. new listeners). Since it is not returning I don't see a good way to implement it as in instance funcion (i.e. pass it the object). I could probably not let the sample function run continously but call it periodically from outside. However I planned to implement the class as a singleton, so it could be used parallely from different VIs.
    Is there a best practice for a case like this?
    I'm glad about any hints or ideas.
    Thanks,
    Tobias

    tfritz wrote:
    Hi,
    thanks. Since almost the same thing was suggested to me in a German forum I guess this is really common practice (using one VI with different methods controlled by a queue). It still seems a little "unnatural" for me but my biggest concern (bad interface description) was shattered by the suggestion in the link you sent me to wrap these functions with wrapper VIs, thus caller VIs won't have to deal with the call-by-queue-mechanism. This might also be easier to port to a different implementation later. However I still see the danger that the continously running VI could easily become bloated. 
    It also requires me to change the way I have looked at VIs until now. In our course they told us that VIs are basically functions. Using this design patterns, the VI becomes more of a module, really (Like a C module implemented in a C-Source file). But I will try it. It sounds as if it could work.
    I will still look into the OOP solutions a little more, though. Do I understand you correctly that you wouldn't recommend using LVOOP because it's still buggy? What about dqGOOP for example? This sounds like it could do what I need (however it doesn't seem to implement things like polymorphism, late binding and inheritance so I don't quite see what's so OOP about it. It seems more like programming with structures in C.)
    I don't know if LVOOP is buggy or not.  I think early on it was buggy and things have improved in recent versions. I have read that it doesn't have all the features that you would have in OOP like C.  I wouldn't recommend it only because I'm not familiar with it at all.  I can't recommend something that I'm not comfortable with.  If you go that route, plan on spending time in these forums and in LAVA to reading up on what others have done.  I haven't hard of dqGOOP.
    But back to your suggestion. I still have a couple of questions:
    - How do you return values from the module? Would you use a queue for that as well?
    - Where would the parameter queue be held (created and passed to the VI)
     I would store all of these in a functional global variable.  This is the VI that stores data in shift registers.  Ben's action engine nugget is an advancement on that.  This allows for both the calling VI and the parallel running subVI to get and set the data as needed.  It runs quickly so neither process should be forced to wait while the other  VI is doing its thing.
    - My VI has to be constantly sampling and this shouldn't be interrupted too long by other functions as adding a listener. However both functionalities have to access the same kind of data. Is there an easy way to parallelize this? Would the sampling be a case in the case diagram that's always used if no command was sent to the VI or would it somehow run parallely?   Yes.  There are a couple of ways of doing this.  One would be for the dequeue to have a timeout function.  In the event the dequeue times out, you run the code that is doing the acquisition.  I think a better method is that the code that does the acquisition enqueues its own command again to the end of the queue.  Let's say that is command A.  So when case A finishes, it enqueues A, which seeds itself to run again.  So if nothing else comes into the queue, it just executes A , A, A, A.  But let's say another section of code needs to do something such as command B.  It will slip B into the queue while A is executing.  So you would A, B, then A again, because A would get slipped back into the queue when the first A finishes, but B has already been put in while the first A was running.
    - Would it be possible to make the VI reentrant and in this way use it simultaneously on different COM ports (using different parameter queues as well)? I'm not sure if I will need this but it would be neat if it could work.
    I think you could do this.  It may be a case where the VI is saved as a template  (.vit) and you initiate it multiple times.  I haven't needed to do this before, so I'm afraid I can't provide any details or useful tips. 
    Well, I will fool around some more. Thanks so much for your help. This is kind of exciting since the concepts are quite new for me. Btw, is there something like an academic theory (computer science) for LabVIEW? I came across functional languages in university but data flow languages are still a new concept for me.
    Tobias
    tfritz wrote:
    Another question about the "dynamically starting" of the VI:
    How is the path handled? Is it guaranteed that it always takes the VI from the project or does it just search for the first VI by that name it finds in the file structure? Does this still work when building an .exe from the project? What happens if the VI is already running? Can you test for this?
    While I'm at it: is there a way to stop LabVIEW from searching for subVIs it can't find when openin a VI? This resulted in very unexpected behaviour sometimes where it would find the VI somewhere else (with the same name but maybe an older version).
    In my case, I just had the path hardcoded.  It is my only instance, I'm not planning on moving the VI's.  If you don't have the path, it will take a VI by that name if it's in memory.  If it isn't in memory, it starts searching relative to the calling VI's path.  One thing I know, if you are dealing with relative paths, a subVI has a different relative path in an .exe as opposed to the development environment.  The name of the .exe becomes a folder.  So in development, if your sub VI is mySubVI.vi.  In an executable, its path is MyExe.exe\MySubVI.vi
    For all of this, I recommend searching the forums to get more details.
    If it is searching for a VI, you can hit ignore.  But of course you'd have to do it before it finds it.  When you are dealing with versioning issues, I recommend making a backup copy of the entire directory structure elsewhere.  Some location where it shouldn't stumble across it.

Maybe you are looking for

  • Mini-VGA to S-video only gives a black&white tv-screen.

    When I connect my emac G4 with a video adapter (through mini-VGA) to the S-video port of my tv it doesn't have any colour. How can I change this? The image is perfect but its just black and white.

  • Function module to give all partner functions for given customer

    Can anyone tell me function module name which gives all partner functions for a customer. For ex if we give customer number and sales area then it should give the list of all partner functions of this customer. I know 'CUSTOMER_PARTNERFS_GET' functio

  • How do I get fancybox 2 to NOT loop?

    I'm putting together a site that involves a lightbox (fancybox 2). It works great. One change I made for the client was in the CSS so that the previous and next arrows would be "visible" all the time, rather than only when hovering over the box. Seem

  • ABAP proxy (Client proxy)

    Hi all, Could you provide an insight onto how the ABAP proxy on the client side works? What i want to know is, 1. How do we trigger the proxy. (in case of file -> abap proxy , when ever we pick the file and once the message is inside the XI and sent

  • ITunes error msg file not win32 app

    I've tried downloading iTunes 10.1.2 and installing. Each time I get a message that the file is not a win32 application. Any suggestions on what would would cause this? Message was edited by: smithgary1