Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

How to exit and restart this server.

Posted on 2004-10-27
9
Medium Priority
?
241 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
Comment
Question by:delphi3
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 2

Expert Comment

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

Expert Comment

by:Giant2
ID: 12430710
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
ID: 12431251
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 12

Expert Comment

by:Giant2
ID: 12432929
>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
ID: 12440684
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
ID: 12441738
What is your code now?
0
 
LVL 4

Author Comment

by:delphi3
ID: 12441829
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:
Giant2 earned 200 total points
ID: 12441937
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
ID: 12448147
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

636 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