Solved

How to exit and restart this server.

Posted on 2004-10-27
239 Views
Last Modified: 2011-09-20
Hi All,
This is not homework.

Given the server sample code below, the server opens to a call from the client,  and delivers the data. However  I would like to know what code to add for a close when  the data is finished being sent,  then be able to reopen it again upon another call to it.

Thanks in advance for your response.

Delphi3

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

// use applicPxlgrabMTstoBytes.java to make ColorPixlData.txt

public class localHostServerImage extends JFrame
{  
  private JTextField textConnection;
  private JLabel labelConnection;
  Container container = null;
  Vector vec1;
  Vector vec2;
  int b = 0;
 
 
  public localHostServerImage()    
  {    
    container = getContentPane() ;
    container.setLayout(new FlowLayout());
   
    labelConnection = new JLabel("Connection ") ;
    container.add(labelConnection );
    textConnection = new JTextField(15) ;
    container.add(textConnection);
    textConnection.setText("Disconnected");
   
    setSize ( 200,400) ;
    setVisible(true);
    try {
      FileInputStream fin = new FileInputStream("ColorPixlData.txt");
      ObjectInputStream inOStrm = new ObjectInputStream(fin);
      //image dimensions
      vec1 = (Vector) inOStrm.readObject();
      //image pixlColors
      vec2 = (Vector) inOStrm.readObject();
      inOStrm.close();
    }
    catch (Exception e) {
      System.out.println("error getting data");
    }
    try
    {
      //creating server socket binding at port # 3000
      ServerSocket server=new ServerSocket(3000);
      System.out.println("Server binded at "+((server.getInetAddress()).getLocalHost()).getHostAddress()+":3000");
      System.out.println("Run the Client");
      //ready to accept client request
      Socket socket=server.accept();
      textConnection.cut();
      textConnection.setText("Connected\n");
     
     
      //opening the input stream to read data from client connection
      BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
      System.out.println(in.readLine());
      //using output stream responsing data
      ObjectOutputStream out=new  ObjectOutputStream(socket.getOutputStream());
     
      while ((true)&&(b<1))
      {
        out.writeObject(vec1);
        //System.out.println(vec1);
        out.writeObject(vec2);
        //System.out.println(vec2);
        out.flush();
        out.close();
       ++ b;
      }
      //closing the in & out streams
    }
    catch(Exception err)
    {
      System.err.println("* err"+err);
      textConnection.cut();
      textConnection.setText("Disconnected\n");
    }
  }
 
  public static void main(String a[])
  {
    new localHostServerImage();
  }  
}
0
Question by:delphi3
    9 Comments
     
    LVL 2

    Expert Comment

    by:fredwangus
    if (!server.isClosed()){server.close();}
    0
     
    LVL 12

    Expert Comment

    by:Giant2
    You must create a loop (be sure to use a condition of exit) before the accept call method.
    In this manner you can have a connection opened and accept each time a new "message".

    Hope this help you.
    0
     

    Expert Comment

    by:nigelsheldon
    Dude, don't close the server after your clients request has completed, just the in and out streams. You will have to be poling that port for more connections. If you want the thread to be domant then make it runnable and sleep() until a socket connection is received.
    0
     
    LVL 12

    Expert Comment

    by:Giant2
    >don't close the server after your clients request has completed
    I didn't say this.
    I told to create a loop and have a connection opened (one for all).
    0
     
    LVL 4

    Author Comment

    by:delphi3
    Hi All,
    While your instructions read as reasonable, I have tried many placements of them within my program above but have not caused the program to code to provide for a close when  the data is finished being sent, then be able to reopen it again upon another call to it.
    Further help is appreciated.

    D3
    0
     
    LVL 12

    Expert Comment

    by:Giant2
    What is your code now?
    0
     
    LVL 4

    Author Comment

    by:delphi3
    Giant2,
    Thanks for responding.
     I gave a working model above that delivered the vectors as intended.... on a  one time through: the server gets a request from the client and then  the server delivers the required vectors.

    Any additions suggested above that I did to it makes it not work as delivering the vectors.
    Here is my server and the client.

    Server......

    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;

    // use applicPxlgrabMTstoBytes.java to make ColorPixlData.txt

    public class localHostServerImage extends JFrame
    {  
      private JTextField textConnection;
      private JLabel labelConnection;
      Container container = null;
      Vector vec1;
      Vector vec2;
      int b = 0;
     
     
      public localHostServerImage()    
      {    
        container = getContentPane() ;
        container.setLayout(new FlowLayout());
       
        labelConnection = new JLabel("Connection ") ;
        container.add(labelConnection );
        textConnection = new JTextField(15) ;
        container.add(textConnection);
        textConnection.setText("Disconnected");
       
        setSize ( 200,400) ;
        setVisible(true);
        try {
          FileInputStream fin = new FileInputStream("ColorPixlData.txt");
          ObjectInputStream inOStrm = new ObjectInputStream(fin);
          //image dimensions
          vec1 = (Vector) inOStrm.readObject();
          //image pixlColors
          vec2 = (Vector) inOStrm.readObject();
          inOStrm.close();
        }
        catch (Exception e) {
          System.out.println("error getting data");
        }
        try
        {
          //creating server socket binding at port # 3000
          ServerSocket server=new ServerSocket(3000);
          System.out.println("Server binded at "+((server.getInetAddress()).getLocalHost()).getHostAddress()+":3000");
          System.out.println("Run the Client");
          //ready to accept client request
          Socket socket=server.accept();
          textConnection.cut();
          textConnection.setText("Connected\n");
         
         
          //opening the input stream to read data from client connection
          BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
          System.out.println(in.readLine());
          //using output stream responsing data
          ObjectOutputStream out=new  ObjectOutputStream(socket.getOutputStream());
         
          while ((true)&&(b<1))
          {
            out.writeObject(vec1);
            //System.out.println(vec1);
            out.writeObject(vec2);
            //System.out.println(vec2);
            out.flush();
            out.close();
           ++ b;
          }
          //closing the in & out streams
        }
        catch(Exception err)
        {
          System.err.println("* err"+err);
          textConnection.cut();
          textConnection.setText("Disconnected\n");
        }
      }
     
      public static void main(String a[])
      {
        new localHostServerImage();
      }  
    }


    Client......

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.BevelBorder;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.net.Socket;
    import java.util.*;


    // image via localhost, run server first.
    public class localHostClientImageOnPanel
      extends JPanel {  
      DataInputStream in = null;
      ObjectInputStream inOIS= null;
      Vector vec1,vec2;
      int b= 0;  
      String hR, hG, hB, width, height, hexColor;
      int red, green, blue, dx, dy,  w, h;
     
      private static final String title = "Image On Panel Using Localhost";
      private static final int widthPanel = 300;
      private static final int heightPanel = 300;
      JPanel imagePanel = new JPanel();
     
      // Constructor
      public localHostClientImageOnPanel() {
        this.setLayout(new BorderLayout());
        imagePanel = new JPanel() {
          protected void paintComponent(Graphics g) {
            if (b<1){
              try {
                //ceating the socket to connect to server running on same
                // machine binded on port no 3000
                Socket client = new Socket("localhost", 3000);
                System.out.println("Client connected ");
               
                //getting the o/p stream of that connection
                PrintStream out = new PrintStream(client.getOutputStream());
                //sending the message to server
                out.print("Hello from client\n");
                out.flush();
                //reading the response using input stream
                inOIS = new ObjectInputStream(client
                                                .getInputStream());
               
              } catch (Exception err) {
                System.err.println("* err" + err);
              }
            }
            if (b<1){
              try {
                vec1 = (Vector) inOIS.readObject();
                //System.out.println(vec1);
                vec2 = (Vector) inOIS.readObject();
               //System.out.println(vec2);          
              }        
              catch (Exception e) {
                System.out.println("error getting data");
              }        
              ++b;
            }
           
            width = (String) vec1.elementAt(0);
            w = Integer.parseInt(width);
            //System.out.println(w);
            height = (String) vec1.elementAt(1);
            h = Integer.parseInt(height);
            int index = 0;
           
            for (int y = 0; y < h; y++) {
              for (int x = 0; x < w; x++) {
                hexColor = (String) vec2.elementAt(index);
                hR = hexColor.substring(0, 2);
                hG = hexColor.substring(2, 4);
                hB = hexColor.substring(4, 6);
               
                red = Integer.parseInt(hR, 16);
                green = Integer.parseInt(hG, 16);
                blue = Integer.parseInt(hB, 16);
               
                Color clr = new Color(red, green, blue);
                g.setColor(clr);
               
                // screen reposition dx,dy
                dx = 20;
                dy = 30;
                // used a drawLine with the from and to being the same
                // only a pragmatic solution
                g.drawLine(x + dx, y + dy, x + dx, y + dy);
                ++index;
              }
            }
          }        
        };
        this.add(imagePanel, BorderLayout.CENTER);
        // added this border stuff in 8/06/04
        BevelBorder loweredBevelBorder = (BevelBorder)BorderFactory.createLoweredBevelBorder();
        this.setBorder(loweredBevelBorder);
      }
     
      public void showFrame() {
        JFrame myFrame = new JFrame(title);
        myFrame.getContentPane().add(this, BorderLayout.CENTER);
        myFrame.pack();
        myFrame.setSize(new Dimension(widthPanel, heightPanel));
        myFrame.setVisible(true);
      }
     
      public static void main(String[] args) {
        localHostClientImageOnPanel localHostClientImageOnPanel = new localHostClientImageOnPanel();
        localHostClientImageOnPanel.showFrame();
      }
    }

     
    D3


     
    0
     
    LVL 12

    Accepted Solution

    by:
    The server:
    First of all I'll remove the break of the try catch. Remove the following lines:
    >    }
    >    catch (Exception e) {
    >      System.out.println("error getting data");
    >    }
    >    try
    >    {

    for the loop over the server I'll put the while here:
    ...
          //ready to accept client request
          while (true){//<<<<<<<<<<<
          Socket socket=server.accept();
    ...
            //System.out.println(vec1);
            out.writeObject(vec2);
            //System.out.println(vec2);
            out.flush();
            //here I have removed the out.close()
           ++ b;

    ...
          //closing the in & out streams
          in.close();//<<<<<<<<<<<
          out.close();//<<<<<<<<<<<
          socket.close();//<<<<<<<<<<
          }//end while true//<<<<<<<<<<<
        }
        catch(Exception err)

    0
     
    LVL 4

    Author Comment

    by:delphi3
    Hi Giant2,

    Very nice job! It almost made it but for a small detail.

    I add this line to what revisions you have written.  
     while (true){//<<<<<<<<<<<
            b = 0;//>>>>>>>>> Delph3 added this
            Socket socket=server.accept();

    Running the client repeatedly now makes  versions of the image while the server running. It now works great in my estimation!

    For those interested here is the completed, revised code as far as I want to take it with this Q.

    import java.net.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;

    // use applicPxlgrabMTstoBytes.java to make ColorPixlData.txt

    public class localHostServerImage extends JFrame
    {  
      private JTextField textConnection;
      private JLabel labelConnection;
      Container container = null;
      Vector vec1;
      Vector vec2;
      int b = 0;
     
     
      public localHostServerImage()    
      {    
        container = getContentPane() ;
        container.setLayout(new FlowLayout());
       
        labelConnection = new JLabel("Connection ") ;
        container.add(labelConnection );
        textConnection = new JTextField(15) ;
        container.add(textConnection);
        textConnection.setText("Disconnected");
       
        setSize ( 200,400) ;
        setVisible(true);
        try {
          FileInputStream fin = new FileInputStream("ColorPixlData.txt");
          ObjectInputStream inOStrm = new ObjectInputStream(fin);
          //image dimensions
          vec1 = (Vector) inOStrm.readObject();
          //image pixlColors
          vec2 = (Vector) inOStrm.readObject();
          inOStrm.close();
         
          //creating server socket binding at port # 3000
          ServerSocket server=new ServerSocket(3000);
          System.out.println("Server binded at "+((server.getInetAddress()).getLocalHost()).getHostAddress()+":3000");
          System.out.println("Run the Client");
          //ready to accept client request
          while (true){//<<<<<<<<<<<
            b = 0; //>>>>>>>>> Delph3 added this
            Socket socket=server.accept();
            textConnection.cut();
            textConnection.setText("Connected\n");
           
           
            //opening the input stream to read data from client connection
            BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println(in.readLine());
            //using output stream responsing data
            ObjectOutputStream out=new  ObjectOutputStream(socket.getOutputStream());
           
            while ((true)&&(b<1))
            {
              out.writeObject(vec1);
              //System.out.println(vec1);
              out.writeObject(vec2);
              //System.out.println(vec2);
              out.flush();
              //out.close();
              ++ b;
            }
            //closing the in & out streams
            in.close();//<<<<<<<<<<<
            out.close();//<<<<<<<<<<<
            socket.close();//<<<<<<<<<<
          }//end while true//<<<<<<<<<<<    
        }
        catch(Exception err)
        {
          System.err.println("* err"+err);
          textConnection.cut();
          textConnection.setText("Disconnected\n");
        }
      }
     
      public static void main(String a[])
      {
        new localHostServerImage();
      }  
    }


    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Suggested Solutions

    Title # Comments Views Activity
    core java. isInteger methods. Finding bug. 10 49
    withoutTen challenge 14 51
    nested class vs inner class 5 24
    countPairs challenge 7 14
    After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
    For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
    Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
    Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

    884 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now