Client Socket Reconnect Question

I have a client that is connecting a socket to a piece of hardware (Computer Controlled Telescope). No guarantee that the hardware is powered up when the app starts and the hardware might power down and back up at any time.
The app�s main thread creates a socket to the device. A child thread gets the socket�s OutputStream to send commands to the device. Another child thread gets the socket�s InputStream to receive status from the device.
Problem: How do I recognize that the device has died? What do I have to do to the socket to reconnect it?

I only pass the InputStream and OutputStream to my child threads. The Socket stays snug and secure in my main thread.
Also, I don't want to hide the fact the socket has gone away, just the opposite , I want to know that the socket has died (Socket.isConnected(), I guess), recreate it to the same IP address, and re-distribute the In/Out Streams to the child threads.
I guess my questions are: 1) How can I tell that the thread has died? and 2) How do I recreate the socket?

Similar Messages

  • How to detect client socket shutdowns in server socket

    Hi,
    Hoping to get some help with this. I am writing this program that implements a socket server that accepts a single client socket (from a third-party system). This server receives messages from another program and writes them to the client socket. It does not read anything back from the client. However, the client (which I have no control over) disconnects and reconnects to my server at random intervals. My issue is I cannot detect when the client has disconnected (normally or due to a network failure), hence am unable to accept a fresh connection from the client. Here's my code for the server.
    ServerSocket serverSocket = null;
    Socket clientSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    try{
              if (serverSocket == null){
                    serverSocket = new ServerSocket(4511);
         clientSocket = serverSocket.accept();
         System.out.println("Accepted client request ... ");
         out = new PrintWriter(clientSocket.getOutputStream(), true);
         in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
         System.out.println("Input / Output streams intialized ...");          
         while (true){                              
              System.out.println("Is Client Socket Closed : " + clientSocket.isClosed());
              System.out.println("Is Client Socket Connected : " + clientSocket.isConnected());
              System.out.println("Is Client Socket Bound : " + clientSocket.isBound());
              System.out.println("Is Client Socket Input Shutdown : " + clientSocket.isInputShutdown());
              System.out.println("Is Client Socket Output Shutdown : " + clientSocket.isOutputShutdown());
              System.out.println("Is Server Socket Bound : " + serverSocket.isBound());
              System.out.println("Is Server Socket Closed : " + serverSocket.isClosed());
              messageQueue = new MessageQueue(messageQueueDir+"/"+messageQueueFile);
              //get Message from Queue Head (also removes it)
              message = getQueueMessage(messageQueue);
              //format and send to Third Party System
              if (message != null){
                             out.println(formatMessage(message));
                   System.out.println("Sent to Client... ");
              //sleep
              System.out.println("Going to sleep 5 sec");
              Thread.sleep(5000);
              System.out.println("Wake up ...");
    }catch(IOException ioe){
         System.out.println("initSocketServer::IOException : " + ioe.getMessage());
    }catch(Exception e){
         System.out.println("initSocketServer::Exception : " + e.getMessage());
    }I never use the client's inputstream to read, although I have declared it here. After the client is connected (it enters the while loop), it prints the following. These values stay the same even after the client disconnects.
    Is Client Socket Closed : false
    Is Client Socket Connected : true
    Is Client Socket Bound : true
    Is Client Socket Input Shutdown : false
    Is Client Socket Output Shutdown : false
    Is Server Socket Bound : true
    Is Server Socket Closed : false
    So, basically I am looking for a condition that detects that the client is no longer connected, so that I can bring serverSocket.accept() and in and out initializations within the while loop.
    Appreciate much, thanks.

    Crossposted and answered.

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

  • Socket reconnection issue

    Hi,
    our aim of using the sockets is to send the HL7-message to HL7-engine.
    while reconnecting to the engine(server) i am following the steps
    1. close the outputstream of the socket
    ( socket.getOutputStream().close() )
    2. close the socket
    ( socket.close() )
    3. wait for 2 minutes and
    4. create the socket and connect to engine
    imedxORUChannel = new Socket();
    imedxORUChannel.connect(new InetSocketAddress(getREMOTEHOST(), getREMOTEPORT()));
    5. sometimes client socket is getting connected to server , sometimes not.
    i want the socket to connect to remote host with in small span of time.
    can any one provide the solution for this.
    thanks in advance .

    while reconnecting to the engine(server) i am following the steps
    1. close the outputstream of the socket
    ( socket.getOutputStream().close() )
    2. close the socket
    ( socket.close() )Unnecessary if you've closed the output stream.
    3. wait for 2 minutes and Why?
    5. sometimes client socket is getting connected to server , sometimes not.What exception is thrown when it fails? Show the complete exception text.
    i want the socket to connect to remote host with in small span of time.It should connect within seconds, or fail after not more than about 75 seconds. You can reduce that timeout by calling the connect() method that takes a timeout parameter.

  • Sockets  & JMF Question

    I have created a voice chat application.
    1.It uses the Sockets for updating the clients about new user logging in /logging out..etc.,
    2.The transmitter uses the IPAddress information sent to the client by the Server to create specific session for transfer of media.
    My question is How do I make it work on a internet environment where the client machines does not have a static IP address. How do I make the Server and Client sockets communicate over the internet on dynamically allocated IPs.
    Any help will be appreciated !

    In the world of distributed applications, usually one lets the
    (dynamic IP address having) client let the server know it's up and
    awake and ready for action. To obtain, inside java, the local
    IP address of the host, there's a rather outdated API (which thinks
    that machines can only have one address for some reason); the
    java.net.InetAddress.getLocalHost().getHostAddress().toString()
    kind-of-jobby works fine for me (on WIN#@!);
    however it could well be that this thing just returns '127.0.0.1'
    on my UNIX box at home (in the UNIX world it's quite common for a box to have multiple addresses), which given the method-name
    ('getLocalHost') would be very intuitive for me (127.0.0.1 IS
    localhost in IP-land.)
    But I'm not too sure; I'll let you know because I have to test this
    stuff out on multiple boxen anyway.
    Oh and I would like for this post to encourage the java-people at
    Sun to implement an API that goes about like this:
    package java.net;
    class InetAddress {
    static InetAddress[] getLocalAddresses();
    PLEASE !

  • When does the RMI Client socket be created?

    Hi, I have created my own RMIClientSocketFactory and RMIServerSocketFactory, it was just a normal socket with some print statements. Example:
    ============================================================
    public class MyRMIClientSocketFactory implements
    RMIClientSocketFactory, Serializable {
    private int hashCode = "MyRMIClientSocketFactory".hashCode();
    public Socket createSocket(String host, int port) throws IOException {
    System.out.println("creating socket to host : " + host + " on port " + port);
    return new Socket(host, port);
    public boolean equals(Object object) {
    if (object instanceof MyRMIClientSocketFactory)
    return true;
    return false;
    public int hashCode() {
    return hashCode;
    public class MyRMIServerSocketFactory implements RMIServerSocketFactory, Serializable {
    private int hashCode = "MyRMIServerSocketFactory".hashCode();
    public ServerSocket createServerSocket(int port) throws IOException {
    System.out.println("creating ServerSocket on port " + port);
    return new ServerSocket(port);
    public boolean equals(Object object) {
    if (object instanceof MyRMIServerSocketFactory)
    return true;
    return false;
    public int hashCode() {
    return hashCode;
    ================================================================
    I wonder when the message "creating socket on port.." and "creating ServerSocket on port.." will be printed? And I found that the equals() and hashCode() methods are called quite a lot of times when I made one rmi call. When I keep the reference of the remote object for some times, the client socket will be created again. Can somebody tell me how all these work?
    Thanks,
    Jax

    Does it
    means that when timeout happened, a new client socket
    will be created and make remote calls to renew DGC
    leases?Yes.
    Again, about exporting remote objects on the same
    port, why I got the exceptions:
    java.rmi.server.ExportException: Port already in use:
    1234;
    nested exception is: java.net.BindException: Address
    already in use: JVM_BindYou get this if you try to export two servers on the same port but their server socket factories are not equal (or not both null or unspecified), or if the two ojbects are in separate JVMs (port sharing can only work inside a single JVM), or if the port is in use by some other listening process.
    Your MyRMIServerSocketFactory.equals() method looks OK to me, but I'd delete the hashCode() method, it's not necessary for RMI and your implementation is flawed. Personally I use the following equals() method:
    public boolean equals(Object that) { return that != null && that.getClass() == this.getClass(); }

  • AM Client java file question.

    Hello,
    I am learning OAF, when configured an AM to expose methods by Client Interface, a java file is created under /client, a reference is also made in the AM.xml:
      ComponentClass="...server.PeRatingAMImpl"
       ComponentInterface="...server.common.PeRatingAM"
       ClientProxyName="...server.client.PeRatingAMClient"The questions:
    1. Do I have any use for ClientProxyName java file or it is there to serve as adapter/glue code between my interface (AM.java and AMImpl.java?
    (Depends on answer to Q1)
    2. I'm suppose to use in my controller the AM.java, or the generated AMClient?
    Thanks in advance.

    What you will do in your controller is get a reference to the AM via the pageContext object.
    Like this:
    OAApplicationModule am=(OAApplicationModule)pageContext.getRootApplicationModule();
    Use the am ref to call methods in the am.
    Kristofer Cruz

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

  • Can VPN Client automatically reconnect to virtual cluster IP..

    Can VPN Client automatically reconnect to virtual cluster IP when current ASA fail or users must manually reconnect in VPN load balancing implementation?
    Thank you in advance
    Sirote

    In my ASA 7.2 config, there is no "management-access inside" command, but it still work. Anyway, after I added this command in my ASA 8.0 config, it work. Thanks a lot.

  • 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

  • Socket Communication Question

    Hi, I am new to using sockets and somewhat new to Java in general.
    How does one go about setting up a client/server system so that:
    - The server will wait for connections
    - After it accepts the connection, will read the first request sent
    - After interpreting this request, I'd like to send a reponse BACK to the client
    - After receiving this response, the client will UPLOAD a file over the socket
    I've got a https server a client running, but it is more of a single response per request kind of setup. Sorry if this seems like a silly question, I am somewhat new.
    Chuck Reed

    * PingServer.java
    * Created on December 1, 2001, 1:47 PM
    package com.sas.planetation.servers.ping;
    import com.sas.util.socket.*;
    import com.sas.planetation.data.*;
    import com.sas.planetation.exceptions.*;
    import com.sas.planetation.servers.*;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    * @author  Scott Shaver
    * @version
    public class PingServer implements ClientConnectionHandler, CommandInputListener{
        public static final String CONFIG_FILE_NAME = "pingserver.cfg";
        public static final String PROP_LISTEN_PORT = "pingserver.listeningport";
        public static final String PROP_ADMIN_PORT = "pingserver.adminport";
        public static final String PROP_BYTE_COUNT = "pingserver.sendbytecount";
        private Properties properties = null;
        private MultiSocketServer pingSocket = null;
        private MultiSocketServer adminSocket = null;
        private int pingPort = 0;
        private int adminPort = 0;
        private int pingByteCount = 0;
        private CommandInput cmdInput = null;
        private String configDirectory = null;
        /** Creates new PingServer */
        public PingServer(String configDir) {
            super();
            configDirectory = configDir;
        public void setPingSocket(MultiSocketServer server) {
            pingSocket = server;
        public void setAdminSocket(MultiSocketServer server) {
            adminSocket = server;
        public MultiSocketServer getPingSocket() {
            return pingSocket;
        public MultiSocketServer getAdminSocket() {
            return adminSocket;
        public void setPingByteCount(int count) {
            pingByteCount = count;
        public void setPingPort(int port) {
            pingPort = port;
        public void setAdminPort(int port) {
            adminPort = port;
        public int getPingPort() {
            return pingPort;
        public int getAdminPort() {
            return adminPort;
        public Properties getProperties() {
            return properties;
        public void startUp() {
            try
                postMessage("-------------------------------------");
                postMessage("Planetation Ping Server");
                postMessage("-------------------------------------");
                postMessage("Loading configuration.");
                properties = loadConfiguration();
                String data = getProperties().getProperty(PROP_BYTE_COUNT);
                int bc = Integer.parseInt(data.trim());
                if(bc<0 || bc>127)
                    bc=1;
                postMessage("Setting ping byte count to "+bc+".");
                if(data!=null)
                    setPingByteCount(bc);
                data = getProperties().getProperty(PROP_LISTEN_PORT);
                if(data!=null)
                    setPingPort(Integer.parseInt(data.trim()));
                postMessage("Setting client listening port to "+getPingPort()+".");
                setPingSocket(new MultiSocketServer(this,getPingPort()));
                postMessage("Starting client listening thread.");
                getPingSocket().start();
                data = getProperties().getProperty(PROP_ADMIN_PORT);
                if(data!=null)
                    setAdminPort(Integer.parseInt(data.trim()));
                postMessage("Setting admin listening port to "+getAdminPort()+".");
                setAdminSocket(new MultiSocketServer(this,getAdminPort()));
                postMessage("Starting admin listening thread.");
                getAdminSocket().start();
                postMessage("Server is started and ready.");
                postMessage("-------------------------------------");
                cmdInput = new CommandInput(this);
                cmdInput.startUp();
            catch(Exception x)
                postMessage("Error during server boot.\n"+x);
                System.exit(0);
        * @param args the command line arguments
        public static void main (String args[]) {
            if(args.length!=1)
                System.out.println("Error: Directory location of the config file must be provided.");
                return;
            PingServer ps = new PingServer(args[0]);
            ps.startUp();
        public void postMessage(String msg) {
            System.out.println(msg);
        public Properties loadConfiguration() throws ConfigNotFoundException {
            Properties properties = new Properties();
            File cf = new File(configDirectory,CONFIG_FILE_NAME);
            if(!cf.canRead())
                throw new ConfigNotFoundException("Read permissions not set for "+cf.toString()+".");
            try
                FileInputStream fis = new FileInputStream(cf);
                BufferedInputStream bis = new BufferedInputStream(fis);
                properties.load(bis);
                bis.close();
            catch(Exception x)
                throw new ConfigNotFoundException("Error reading "+cf.toString()+".\n"+x);
            return properties;
         * Called when a client connection is accepted in the run method.
         * Sub-classes of this class should define this method to handle
         * the client requests. Note that while this method is being executed
         * no more client connections will be accepted so this method must
         * complete quickly.
        public void handleClientConnection(SocketServer server, Socket s) {
            if(server.getPort()==getPingPort())
                postMessage("Received client connection.");
                PingServerClientThread ct = new PingServerClientThread(s,pingByteCount);
            else if(server.getPort()==getAdminPort())
                postMessage("Received admin connection.");
                try
                    DataInputStream is = new DataInputStream(s.getInputStream());
                    int type = is.readInt();
                    switch(type)
                        case CommunicationDataTypes.SERVER_STOP:
                            ServerStop ss = new ServerStop();
                            ss.readData(is);
                            shutDownServer();
                            break;
                catch(IOException x)
                    postMessage("Error reading admin connection data.\n"+x);
                catch(InvalidFileFormatException iffx)
                    postMessage("Error reading admin connection data. InvalidFileFormatException\n"+iffx);
        public void shutDownServer() {
            postMessage("Stopping server.");
            pingSocket.stop();
            adminSocket.stop();
            cmdInput.stop();
            System.exit(0);
        public void handleCommandInput(String cmd) {
            postMessage("Processing Command: "+cmd);
            if(cmd.equals("stop"))
                shutDownServer();
            else if(cmd.equals("?") || cmd.equals("help"))
                postMessage("stop - shutdown the server");
                postMessage("? or help - show the command help");
            else
                postMessage("Command is not recognized. Type help or ? for command list.");
    }

  • Socket Reconnect

    Hi, I've written a very basic chat program in my efforts to learn more about socket programming in Java, I'm having a slight bit of trouble though.
    The problem is that when the client disconnects, it cannot reconnect again unless both the server and client are restarted. I'm looking to fix this so that the client can disconnect and reconnect as many times as they like because later I'll be adding the abuility for many clients to connect and disconnect.
    The code is abit large to be posted here but it's availiable on sourceforge at
    http://sourceforge.net/projects/roxcom/
    if you'd like to take a look.
    Thanks for any help in advance.
    Ross

    Ok, this method seems to work fine however, if teh client disconnects from the server, the server needs to try and send text before it will find the error, close and start waiting for the next client. The only way I can think to get round this is to send some sort of SYN<->ACK strings. Is this right?
    out.println(txString);
    if (out.checkError())     // Changed for flush()
        if (!isHost())
          disconnect();
        else
            try{
                clientSocket.close();
                hostSocket.close();          
            }catch(IOException e) {
                sendDebugString("Error Closing Host");
            status=CREATINGHOST;
            return false;
    else
        return true;
    }

  • Client/Server UDP question

    Hi,
    I am writing a server program which both sends and receives UDP messages to various clients.
    What I want to do is both send and receive on the same port. I'd like the receiving to be done on the same thread (and therefore on the same socket). However I'd like the sending to be done in multiple threads (1 per client).
    The problem is, I don't think I can use the same socket object to send to all of the clients. I'm thinking there would be collisions/problems with the multiple threads sending on the same socket.
    However, if I create multiple sockets for sending, and one socket for receiving (all bound to the same port), is there a way to tell the "sending" sockets to only send (i.e., not receive)? Or is this automatically done simply because I never do a socket.receive on those sockets? Or do I need to pick a different port for sending rather than receiving?
    What I want to avoid is listening to the port on my "listen" socket, but having that data show up on one of my "send" sockets (and therefore never seen, because I don't do a socket.receive()).
    I've looked in the forums/tutorials for this, but nothing I've seen addresses needing to send from multiple threads, or needing to have listening on a separate thread (which I need to do to prevent having the receive() block the send()). Please bear with me if this is a stupid question; I'm new to network programming, especially UDP.
    Any help would be greatly appreciated!

    it shouldn't be a problem to send from multiple threads and receive on another thru the same UDP socket. If you want to send from a different socket, that's fine too... except that the other side will need to know to send responses back to your receiving socket (port) and not the "source" of the packets they receive.
    I'm not sure you can mark the socket for send or receive only, but it really doesn't matter. Just don't read from the sending one or write to the receiving one. An incoming packet isn't going to block an outgoing packet, or an outgoing packet isn't going to push an incoming packet out of the way. The pipe analogy for socket connections isn't so literal like a real pipe where water could only really go one way.
    It's the threads that would block on while waiting for input, which is why you need separate threads, but not necessarily separate sockets.

Maybe you are looking for