Link to home
Start Free TrialLog in
Avatar of delphi3
delphi3

asked on

How to exit and restart this server.

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();
  }  
}
Avatar of fredwangus
fredwangus

if (!server.isClosed()){server.close();}
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.
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.
>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).
Avatar of delphi3

ASKER

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
What is your code now?
Avatar of delphi3

ASKER

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


 
ASKER CERTIFIED SOLUTION
Avatar of Giant2
Giant2

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of delphi3

ASKER

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();
  }  
}