Server Socket Threading

My program does a couple of things, one of the thing it does is it runs a ServerSocket in the background.
The problem is that when I run the my Server class, I can't do anything else since the ServerSocket is stuck in an infinite loop waiting for a new request.
See this:
My Driver
    public static void main(String [] args) {
            new Server();
            new SomethingElse();
    }Server's snippet of code that establishes a connection between a client and server.
     while (true)
                  try
                        Socket clientSocket = serverSocket.accept();
                   catch (IOException e)
                        System.out.println("Could not accept requests.");
                        System.exit(-1);
              }So I can never reach SomethingElse() in the driver since Server is stuck in an infinite loop.
I have tried to implement the ServerSocket as a thread, but the serverSocket throws an IOException (which makes sense since a ServerSocket should not have multiple versions of itself running at a same time unless they are on separate ports).
So how would take care of this?
Edited by: sharpdust on Dec 5, 2008 1:12 PM

How about something like this?
public static void main(String [] args) {
            new Thread(new Server()).start();
            new SomethingElse();
public class Server implements Runnable {
     public void run() {
          while (true)
                  try
                        Socket clientSocket = serverSocket.accept();
                   catch (IOException e)
                        System.out.println("Could not accept requests.");
                        System.exit(-1);
}

Similar Messages

  • Server socket programming and thread

    hello,
    briefly this is what i have sought out to do : the server waits for the client indefinitely,upon a client requesting for service by writing a service id into the socket, a new thread of the type id as read by the server which is a sub-class of the Server (main-class) is exec'd.
    the problem as i understand is that the client can send as much of data as it desires to the server and the thread can read the data it receives by the clients.the server(thread) fails to write reply to the client;eventhough out.write() is successful;the client is blocked in read() indefinitely.is it because of the thread which runs at a different port the client does not know and the server is not redirecting response to the client.
    how do i read what the server(thread) writes onto the socket from the clients.

    thanks again,just check out this code please
    public class Server extends Thread //create a multi-threaded server
        /* *Creates a new instance of Server  */
        String                           serverAddr=CodeServer.ServerRun.SERVER_IP_ADDR;
        int                              serverPortNum=CodeServer.ServerRun.SERVER_TCP_PORT;   
        ServerSocket                     sSock;
        Socket                           cSocket;
        int                              requestID=0;
        boolean                          debug=true;  
        InputStream                      in =null;
        OutputStream                     out=null;
        Server ()
        Server (Socket csocket)
            this.cSocket = csocket;
        /* start the server at specifed portNum */
        private void initialise ()
            try
                //start the server at serverPortNum
                sSock=new ServerSocket (serverPortNum);
            catch (IOException ex)
                ex.printStackTrace ();
            /* console output of status of server */
            if(debug==true)
                System.out.println ("Server waiting @ "+sSock);
        private void acceptRequest ()
            try
                this.cSocket=sSock.accept ();
                if(debug==true)
                    System.out.println ("client socket @ "+cSocket);
            catch (IOException ex)
                ex.printStackTrace ();
        private void readRequestID ()
            /*step 1: determine the type of server before threading
             *a request the the type of server got by the request ID
             * number */       
            try
                in        =cSocket.getInputStream ();
                requestID =in.read ();
                out       =cSocket.getOutputStream ();
                if(debug==true)
                    System.out.println ("accross the client:"+requestID);
            catch (IOException ex)
                ex.printStackTrace ();
        private void execThreadForRequest ()
            /*step 2: after requestID is received on the socket.
             *its time to decide the server to thread the control into.
            switch(requestID)
                case 1: //invoke the RegisterServer thread
                    new CodeServer.Core.RegistrationServer (this.cSocket).start ();
                    break;
                case 2: //invoke the ListingServer thread
                    break;
                case 3: //invoke the MessageTransferServer thread
                    break;
                case 4: //invoke the CallSetupServer thread
                    break;
                case 5: //invoke the DisconnectServer thread
                    break;
                case 6: //invoke the ChangeUserStatusServer thread
                    break;
        public void run ()
            // client processing code here==super class does nothing here
        public static void main (String args[]) throws Exception
            Server s=new Server ();
            s.initialise ();
            /* start indefinitely the main server thread */
            while (true)
               /* accept() blocks the server for a request
                  a new request is put into a thread for processing */
                s.acceptRequest (); //initialise the clientSocket
                s.readRequestID (); //get the actual requested service
                s.execThreadForRequest (); //start the actual server thread
    /**registration service class;
    *registers the IP address of the caller,callee and the status
    *adds the caller to the hash table and updates status
    class RegistrationServer extends Server
        Socket              cSocket;
        InetAddress         clientAddr;
        DataInputStream     inStream;
        DataOutputStream    outStream;
        //Socket s=new Socket()
        RegistrationServer (Socket cSocket)
            this.cSocket=cSocket;
            clientAddr =cSocket.getInetAddress ();
            try
                //init for reading status and custom message.
                inStream     =new DataInputStream (cSocket.getInputStream ());
                outStream    =new DataOutputStream (cSocket.getOutputStream ());
            catch (IOException ex)
                ex.printStackTrace ();
            if(CodeServer.ROO.DEBUG==true)
                System.out.println ("register server:"+cSocket
                                   +" host ip:"+clientAddr.getHostName ());
        public void run ()
            int    status=0;
            String custMesg=null;
            try
                /* read the custom message */
                if(inStream.available ()>0)
                    try
                        custMesg=inStream.readUTF ();
                        System.out.println (""+custMesg);
                    catch(EOFException e)
                        e.printStackTrace ();
                else
                    custMesg="";
            catch (IOException ex)
                ex.printStackTrace ();
                try
                           here is the problem, i found if i try reading accross the client             
                           i only receive a junk value 81 always */
                       outStream.write(1); //write success
                        outStream.flush();
                catch (IOException ex)
                    ex.printStackTrace ();
    }and with the client GUI :thanks for the help.please do find time to help me out with a suggestion or two on this code.

  • Socket threads problem after SOA installation

    Hi all,
    I am getting below error after sending request to the server(after weblogic and SOA servers started properly.
    <Warning><Socket>'There are: '5' active sockets, but the maximum number of
    socket readers allowed by the configuration is: '4', you may want to alter
    your configuration.>'
    I am not able to deploy the application into the SOA Server(I am getting http response 502 error in my Jdeveloper's log).
    I have seen forums about this ,they told to change the socket threads in weblogic console(mine is weblogic 10.3.5 server) ,but I am not able to change in the console.It has already some value as 33 and when I change and save ,it is telling value can not be changed dynamically.
    I was told to change like below.But Where do I need to change like below and how
    java -Dweblogic.ThreadPoolSize=10 -Dweblogic.ThreadPoolPercentSocketReaders=60 ... your.client ...
    I am stuck(I am not able to deploy the applications into SOA server)
    Thanks in advance

    Hi
    1. What you are seeing is <Warning> and mostly you can ignore this. This may not be the root cause for your error.
    2. Can you access your soa server url from browser like http://soahost:soaport/bpm/workspace url should work. Try soahost with direct ip address or dns name of that machine.
    3. In Jdeveloper, when you configure this, I hope you Tested the connection and does it show success.
    4. One way to quickly test is, deploy the SOA Workflow JAR directly from EM Console. The .jar file should be under your soaproject/deploy folder. If you have EAR for TaskForms, deploy EAR also from Console or EM Console. If all this works, this means, JDeveloper is not able to connect to soa server. Search for Proxy settings forJDeveloper in this forum. I remember seeing some posts to enable/disable Proxy for Jdeveloper like that.
    5. Look in the log files for any errors while deployment. But if server itself is NOT accessible, you may not see any deployment errors at all.
    Thanks
    Ravi Jegga

  • Reading text from server socket stream

    I have a basic cd input program i've been trying to figure out the following problem for a while now, the user enters the artist and title etc and then a DOM (XML) file is created in memory this is then sent to the server. The server then echos back the results which is later printed on a html page by reading the replys from the server line by line.
    The server must be run it listens for clients connecting the clients connect and send DOM documents through the following jsp code.
    <%@page import="java.io.*"%>
    <%@page import="java.net.*"%>
    <%@page import="javax.xml.parsers.*"%>
    <%@page import="org.w3c.dom.*"%>
    <%@page import="org.apache.xml.serialize.*"%>
    <%!
       public static final String serverHost = "cdserver";
       public static final int serverPort = 10151;
    %>
    <hr />
    <pre>
    <%
            Socket mySocket = null;          // socket object
            PrintWriter sockOut = null;      // to send data to the socket
            BufferedReader sockIn = null;    // to receive data from the socket
            try {
                //  #1 add line that creates a client socket
                mySocket = new Socket(serverHost, serverPort);
                // #2 add lines that create input and output streams
                //            attached to the socket you just created
                 sockOut = new PrintWriter(mySocket.getOutputStream(), true);
                 sockIn = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
            } catch (UnknownHostException e) {
                throw e; // This time the JSP can handle the exception, not us
            } catch (IOException e) {
                throw e; // This time the JSP can handle the exception, not us
    String cdTitle, cdArtist, track1Title, track1Time, track1Rating;
    // Retrieve the HTML form field values
    cdTitle = request.getParameter("cdtitle");
    cdArtist = request.getParameter("cdartist");
    track1Title = request.getParameter("track1title");
    track1Time = request.getParameter("track1time");
    track1Rating = request.getParameter("track1rating");
    // Create a new DOM factory, and from that a new DOM builder object
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    // Note that we are creating a new (empty) document
    Document document = builder.newDocument();
    // The root element of our document wil be <cd>
    // It gets stored as the child node of the whole document (it is the root)
    Element rootElement = document.createElement("cd");
    document.appendChild(rootElement);
    // Create an element for the CD title called <title>
    Element cdTitleElement = document.createElement("title");
    // Add a text code under the <title> element with the value that
    // the user entered into the title field of the web form (cdTitle)
    cdTitleElement.appendChild(document.createTextNode(cdTitle));
    // Place the <title> element underneath the <cd> element in the tree
    rootElement.appendChild(cdTitleElement);
    // Create an <artist> element with the form data, place underneath <cd>
    Element cdArtistElement = document.createElement("artist");
    cdArtistElement.appendChild(document.createTextNode(cdArtist));
    rootElement.appendChild(cdArtistElement);
    // Create a <tracklist> element and place it underneath <cd> in the tree
    // Note that it has no text node associated with it (it not a leaf node)
    Element trackListElement = document.createElement("tracklist");
    rootElement.appendChild(trackListElement);
    // In this example we only have one track, so it is not necessary to
    // use a loop (in fact it is quite silly)
    // But the code below is included to demonstrate how you could loop
    // through and add a set of different tracks one by one if you
    // needed to (although you would need to have the track data already
    // stored in an array or a java.util.Vector or similar
    int numTracks = 1;
    for (int i=0; i<numTracks; i++) {
      String trackNum = Integer.toString(i+1);
      Element trackElement = document.createElement("track");
      trackElement.setAttribute("id", trackNum);
      trackListElement.appendChild(trackElement);
      // Track title element called <title>, placed underneath <track>
      Element trackTitleElement = document.createElement("title");
      trackTitleElement.appendChild(document.createTextNode(track1Title));
      trackElement.appendChild(trackTitleElement);
      // Track time element called <time>, placed underneath <track>
      Element trackTimeElement = document.createElement("time");
      trackTimeElement.appendChild(document.createTextNode(track1Time));
      trackElement.appendChild(trackTimeElement);
      // Track rating element called <rating>, placed underneath <track>
      Element trackRatingElement = document.createElement("rating");
      trackRatingElement.appendChild(document.createTextNode(track1Rating));
      trackElement.appendChild(trackRatingElement);
    OutputFormat format = new OutputFormat();
    format.setIndenting(true);
    // Create a new XMLSerializer that will be used to write out the XML
    // This time we will serialize it to the socket
    // #3 change this line so that it serializes to the socket,
    // not to the "out" object
    XMLSerializer serializer = new XMLSerializer(writer, format);
    serializer.serialize(document);
            // Print out a message to indicate the end of the data, and
            // flush the stream so all the data gets sent now
            sockOut.println("<!--QUIT-->");
            sockOut.flush();
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String fromServer;
            String fromUser;
             #4 add a while loop that reads text from the
            server socket input stream, line by line, and prints
            it out to the web page, using out.println(...);
            Note that because the reply from the server will contain
            XML, you will need to call upon the toHTMLString() method
            defined below to escape the < and > symbols so that they
            will display correctly in the web browser.
            Also note that as you receive the reply back from the
            server, you should look out for the special <!--QUIT-->
            string that will indicate when there is no more data
            to receive.
            while ((fromServer = sockIn.readLine()) != null) {
            out.println(sockIn.readLine());
                // If the reply from the server said "QUIT", exit from the
                // while loop by using a break statement.
                if (fromServer.equals("QUIT")) {
                    out.println("Connection closed - good bye ...");
                // Print the text from the server out to the user's screen
                out.println("Reply from Server: " + fromServer);
                // Now read a line of text from the keyboard (typed by user)
                fromUser = stdIn.readLine();
                // If it wasn't null, print it out to the screen, and also
                // print a copy of it out to the socket
                if (fromUser != null) {
                    out.println("Client: " + fromUser);
                    sockOut.println(fromUser);
            // Close all the streams we have open, and then close the socket
            sockOut.close();
            sockIn.close();
            mySocket.close();
    %>
    I'm suppose to modify the commented sections labled with #.
    #1,2 are correct but i have doubts on the 3rd and 4th modification.
    for #3 i changed so i serializes to the socket not to the "out" object:
    from
    XMLSerializer serializer = new XMLSerializer(out, format);
    to
    XMLSerializer serializer = new XMLSerializer(writer, format);
    with "out" it prints out some of the results entered but it just hangs i'm thinking it might be the while loop that i added in #4. If i changed it to serialize the socket XMLSerializer serializer = new XMLSerializer(writer, format); it doesn't print out nothing at all; just a blank screen where it hangs.
    I can post the rest of the code (server thats in java and cdinput.html) but since i want to keep my post short and if required i'll post it later on i also omitted some of the code where it creates the DOM textnodes etc to keep my post short.

    On your previous thread, why did you say the server was using http POST and application/xml content type when it quite obviously isn't, but a direct socket communication that abuses XML comments for message end delimiters?
    The comments imply you need to wait for "<!--QUIT-->" on a line by itself, but your loop is waiting for "QUIT".
    Pete

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

  • Problems Reading SSL  server socket  data stream using readByte()

    Hi I'm trying to read an SSL server socket stream using readByte(). I need to use readByte() because my program acts an LDAP proxy (receives LDAP messages from an LDAP client then passes them onto an actual LDAP server. It works fine with normal LDAP data streams but once an SSL data stream is introduced, readByte just hangs! Here is my code.....
    help!!! anyone?... anyone?
    1. SSL Socket is first read into  " InputStream input"
    public void     run()
              Authorization     auth = new Authorization();
              try     {
                   InputStream     input     =     client.getInputStream();
                   while     (true)
                   {     StandLdapCommand command;
                        try
                             command = new StandLdapCommand(input);
                             Authorization     t = command.get_auth();
                             if (t != null )
                                  auth = t;
                        catch( SocketException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection closed: " + e );
                             close( e );
                             break;
                        catch( EOFException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection close: " + e );
                             close( e );
                             break;
                        catch( Exception e )
                             //Way too many of these to trace them!
                             Message.Error( "Command not processed due to exception");
                             close( e );
                                            break;
                                            //continue;
                        processor.processBefore(auth,     command);
                                    try
                                      Thread.sleep(40); //yield to other threads
                                    catch(InterruptedException ie) {}
              catch     (Exception e)
                   close(e);
    2 Then data is sent to an intermediate function 
    from this statement in the function above:   command = new StandLdapCommand(input);
         public StandLdapCommand(InputStream     in)     throws IOException
              message     =     LDAPMessage.receive(in);
              analyze();
    Then finally, the read function where it hangs at  "int tag = (int)din.readByte(); "
    public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
        int tag = public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
           int tag = (int)din.readByte();      // sequence tag// sequence tag
        ...

    I suspect you are actually getting an Exception and not tracing the cause properly and then doing a sleep and then getting another Exception. Never ever catch an exception without tracing what it actually is somewhere.
    Also I don't know what the sleep is supposed to be for. You will block in readByte() until something comes in, and that should be enough yielding for anybody. The sleep is just literally a waste of time.

  • Server Socket does not read data input stream

    Hi all,
    I am very newbie to Java Network programming with sockets and multi-threading.
    But I am obliged to develop a chat system written in Applets which can be placed on the website and used by visitors who come to my website.
    In order to understand this, I have tested a basic web chat program I downloaded from the Internet which use sockets and multi-threadings. The program work fine, no bugs at all at both compilation and run time. I noticed that all three streams for Client side (i.e. first one is input stream used receiving data from User; the second one is socket input stream used for receiving data from Server socket, and the third is socket output stream used for writing data to server socket) were established. And the same, two socket streams (input & output) for Server side were also connected when running program giving right port number and IP address of the server.
    The problem is both server and client sockets do not read data using the following stream classes:
    1. DataStreamInput: I use input.readUTF() method
    2. or BufferedReader: I use input.readLine() method
    The example of the codes are below:
    private BufferedReader input = null;
    private PrintWriter output = null;
    private Socket socket = null;
    public void open() throws IOException
    {  input = new BufferedReader(new
    InputStreamReader(socket.getInputStream()));
    System.out.println("Server socket input stream was created, and");
    output = new PrintWriter(socket.getOutputStream());
    System.out.println("Server socket output stream was created");
    public void run()
    {  System.out.println("Server Thread " + clientPort + " running.");
    while (true)
    {  try
    System.out.println("Server is reading data from Client, wait...");
    String fromClient = input.readLine();
    System.out.println("Server received a message on " + clientPort + ".");
    catch(IOException ioe)
    {  System.out.println(clientPort + " ERROR reading: " + ioe.getMessage());
    server.remove(clientPort);
    stop();
    The problem is at the line: String fromClient = input.readLine(); in the run() method? What is wrong with the codes above?
    Note: I also try to use original codes which use readUTF() method in DataStreamInput class instead using readLine() in BufferedReader. Both methods dont read data from inputstream socket?
    I very appreciate any help/advice from experienced developers.
    Best regards

    Hi,
    Yes. The readLine() method hangs! After the test, the execuation of the program is stopped at the line of readLine() method; it does not pass it?
    There is no problem with writing to Server socket. After the test, the program pass through flush() method. Here is the code for writing to sever socket within ChatClient (client side socket) class:
    private BufferedReader input = null;
    private PrintWriter           output = null;
    public ChatClient(String serverName, int serverPort)
    {  System.out.println("Establishing connection. Please wait ...");
    try
    {  socket = new Socket(serverName, serverPort);
    System.out.println("Connected: " + socket);
    start();
    catch(UnknownHostException uhe)
    {  System.out.println("Host unknown: " + uhe.getMessage()); }
    catch(IOException ioe)
    {  System.out.println("Unexpected exception: " + ioe.getMessage()); }
    public void start() throws IOException
    {  input   = new BufferedReader (new
                             InputStreamReader(System.in));
    System.out.println("Client User input stream was created,");
    output = new PrintWriter(socket.getOutputStream());
    System.out.println("Client Socket output stream was established, and");
    if (thread == null)
    {  client = new ChatClientThread(this, socket);
    thread = new Thread(this);
    thread.start();
    public void run()
         while (thread != null) {
         String fromUser;
              try{
                   while((fromUser = input.readLine())!= null)
                   System.out.println("Client wasreading a data from User, and");
    output.println(fromUser);
         output.flush();
         System.out.println("Client has written a data to Server");
    catch(IOException ioe)
    {  System.out.println("Sending to server error: " + ioe.getMessage());
    stop();
    etc.
    Here is a piece of codes for reading data from the Client Socket in the ChatServer Class (Server Side socket):
    public void run()
    {  System.out.println("Server Thread " + clientPort + " running.");
    while (true)
    {  try
    {  //server.handle(clientPort, input.readLine());
    System.out.println("Server is reading data from Client, wait...");
    String fromUser = input.readLine();
    //while((fromUser = input.readLine()) != null)
         System.out.println("Server received a message on " + clientPort + ".");
    catch(IOException ioe)
    {  System.out.println(clientPort + " ERROR reading: " + ioe.getMessage());
    server.remove(clientPort);
    stop();
    etc. Please advice why the readLine() method hangs; does not read data from the input stream received from the CLIENT?

  • Problem trying to read an SSL server socket stream using readByte().

    Hi I'm trying to read an SSL server socket stream using readByte(). I need to use readByte() because my program acts an LDAP proxy (receives LDAP messages from an LDAP client then passes them onto an actual LDAP server. It works fine with normal LDAP data streams but once an SSL data stream is introduced, readByte just hangs! Here is my code.....
    help!!! anyone?... anyone?
    1. SSL Socket is first read into  " InputStream input"
    public void     run()
              Authorization     auth = new Authorization();
              try     {
                   InputStream     input     =     client.getInputStream();
                   while     (true)
                   {     StandLdapCommand command;
                        try
                             command = new StandLdapCommand(input);
                             Authorization     t = command.get_auth();
                             if (t != null )
                                  auth = t;
                        catch( SocketException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection closed: " + e );
                             close( e );
                             break;
                        catch( EOFException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection close: " + e );
                             close( e );
                             break;
                        catch( Exception e )
                             //Way too many of these to trace them!
                             Message.Error( "Command not processed due to exception");
                             close( e );
                                            break;
                                            //continue;
                        processor.processBefore(auth,     command);
                                    try
                                      Thread.sleep(40); //yield to other threads
                                    catch(InterruptedException ie) {}
              catch     (Exception e)
                   close(e);
    2 Then data is sent to an intermediate function 
    from this statement in the function above:   command = new StandLdapCommand(input);
         public StandLdapCommand(InputStream     in)     throws IOException
              message     =     LDAPMessage.receive(in);
              analyze();
    Then finally, the read function where it hangs at  "int tag = (int)din.readByte(); "
    public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
           int tag = (int)din.readByte();      // sequence tag// sequence tag

    I suspect you are actually getting an Exception and not tracing the cause properly and then doing a sleep and then getting another Exception. Never ever catch an exception without tracing what it actually is somewhere.
    Also I don't know what the sleep is supposed to be for. You will block in readByte() until something comes in, and that should be enough yielding for anybody. The sleep is just literally a waste of time.

  • No exception is thrown when my server socket dies

    I have a server application running on sunOS 5.7.
    To this I have both Windows and SunOS clients connected via TCP/IP. (Server built with jdk 1.2.2 and client with 1.3.0)
    If the Server socket dies an exception is thrown in the windows clients but not in the sunOS client.
    I need the exception to be thrown in the sunOS as well.
    Is there anybody who knows how to get this done?
    Thanks in advance.
    /Henrik

    You could poll the connection to see if its there.
    If you want the client to register the event then have your client create a sort of listener of your own when it connects. By 'sort of listener' I mean extend the thread class and have it check the connection is not null every n seconds. If it is null then raise the exception yourself.
    Would this do it?
    Rob.

  • Should i create a client and a server socket in a same application

    Greetings,
    In which situation sould i have a server socket ? and in which situation should i have a client socket ?and in which situation should i have both?
    I 'm making a app. who receives info (like alarms ) from a automation machine and also that same app. as a scheduler who send commands according to dates to the automation machine.
    Now the automation machine is programmed like a socket tcp/ip server who is always on and the app. is a client.
    Every time there's an alarm the machine sends me the info and i put it in a mysql database.
    Every time there's an event programmed the app. sends a string to the machine.
    The question is that i can't maintain that socket always connected, Sometimes disconnets.
    I was thinking of making the change of creating in both sides a server and a client, so that, for example, in the app. the client woul d handle the event msgs and the server would accecpt connections with alarms from the automaition machine.
    Since i'm a newbie in Java could somebody give me some tips, please?
    Thanks

    Thanks Peter....
    But i already do that....
    I have a thread who handles the connection management.
    If by some reaseon the connection is lost the thread reconnects it.
    My problem is that sometimes it reconnects every second, and i loose info provided by the automatian machine.
    The best thing to have it would be a socket listener, but Java does have any.
    Is there any API that does a socket listener?

  • Client/server socket based application

    hi does anyone have example of client/server socket based application using Spring and Maven
    where application do the following
    Client sends a request with a path to any file on the server
    „h Server reads the file and responds back with the content
    „h Client outputs the content to the console
    am trying to follow this
    http://www2.sys-con.com/itsg/virtualcd/java/archives/0205/dibella/index.html
    http://syntx.io/a-client-server-application-using-socket-programming-in-java/
    am using java 6

    i have attempt code but i wht to do the following
    client/server socket based application that will read the content of a file and stream the content of the file to the client. The client must simply output the content of the file to the console using System.out. The client must be able to run in a standalone mode (non-network mode) or in a remote mode.
    Additionally the client must be designed in a way that i can print the output to a console but must be interchangeable where if requirements change i can persist the response to file or persist the response to a database.
    /* Server.java*/
    ///ifgetBoolen= true then...
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.sql.*;
    public class Server
        static String array[][];
        // STEP 1 a1  
        // Server socket
        ServerSocket listener;
        // STEP 1 a2 Client connection
        Socket client;
        ObjectInputStream in;
        ObjectOutputStream out;
        public void createConnection() throws IOException
                System.out.println("\nSERVER >>> Waiting for connection.....");
                client = listener.accept();
                String IPAddress = "" + client.getInetAddress();
                DisplayMessage("SERVER >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
          public void runServer()
            // Start listening for client connections
            // STEP 2
            try
                listener = new ServerSocket(12345, 10);
                createConnection();
                  // STEP 3
    //              processConnection();
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Error trying to listen: " + ioe.getMessage());
        private void closeConnection()
            DisplayMessage("SERVER >>> Terminating connections");
            try
                if(out != null && in != null)
                      out.close();
                    in.close();
                    client.close();                
            catch(IOException ioe)
                DisplayMessage("SERVER >>> Closing connections");
        public static void define2DArray(ResultSet RS, int Size)
            try
                ResultSetMetaData RMSD = RS.getMetaData();
                DisplayMessage("SERVER >>> Requested arraySize: " + Size);
                if (RS.next())
                    array = new String[Size][RMSD.getColumnCount()];
                    for (int Row = 0; Row < Size; Row++)
                        for (int Col = 0; Col < RMSD.getColumnCount(); Col++)
                            array[Row][Col] = new String();
                            array[Row][Col] = RS.getString(Col+1);
                            DisplayMessage(array[Row][Col] + " ");
                        RS.next();
                else
                    array = new String[1][1];
                    array[0][0] = "#No Records";
            catch (Exception e)
                DisplayMessage("SERVER >>> Error in defining a 2DArray: " + e.getMessage());  
        public static void DisplayMessage(final String IncomingSMS)
            System.out.println(IncomingSMS);
    //client
    * @author
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class ClientSystem
        static Socket server;
        static ObjectOutputStream out;
        static ObjectInputStream in;
        static String Response[][];
        static boolean IsConnected = false;
        static int Num = 0;
        public static void connectToServer() throws IOException
            server = new Socket("127.0.0.1", 12345);
    //        server = new Socket("000.00.98.00", 12345);
            String IPAddress = "" + server.getInetAddress();
            DisplayMessage("\nCLIENT >>> Connected to " + IPAddress.substring(1,IPAddress.length()));
        public static void getStreams() throws IOException
            out = new ObjectOutputStream(server.getOutputStream());
            out.flush();
              in = new ObjectInputStream(server.getInputStream());
              IsConnected = true;
              DisplayMessage("CLIENT >>> Got I/O streams");  
        public static void runClient()
            try
                connectToServer();
                getStreams();
                  DisplayMessage("CLIENT >>> Connection successfull....\n");
                  DisplayMessage("CLIENT >>> Want to talk to server");
            catch (IOException ioe)
                System.out.print("."+Num);
                Num++;
        public static void closeConnection()
            try
                out.close();
                in.close();
                server.close();  
            catch(IOException error)
                DisplayMessage("CLIENT >>> Could not close connections");
        public static void Start()
            System.out.print("\nCLIENT >>> Attempting connection.....");
            try
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    if (IsConnected == false)
                        Thread.sleep(100);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Attempting connection.....");
        public static String sendSMS(String sms)
            Response = new String[0][0];
            try
                DisplayMessage("CLIENT >>> " + sms);
                out.writeObject(sms);
                out.flush();
                Response = (String[][])in.readObject();
                DisplayMessage("CLIENT >>> Waiting for server to respond...");
                for (int Row = 0; Row < Response.length; Row++)
                    System.out.printf( "_SERVER >>> \t");
                    for (int Col = 0; Col < Response[Row].length; Col++)
                        //DisplayMessage( "_SERVER >>> " + Response[Row][Col] + " ");
                        System.out.printf( "%s\t", Response[Row][Col]);
                    System.out.println();
                DisplayMessage("CLIENT >>> Query processed successfully....\n");
            catch(ClassNotFoundException cnfe)
                DisplayMessage("CLIENT >>> Class not found for casting received object");
            catch(IOException ioe)
                reConnect();          
            catch (Exception sqle)
                DisplayMessage("CLIENT >>> Error sending query ??? " + sqle.getMessage());
            return "transmission successfull";
        public static void reConnect()
            try
                DisplayMessage("CLIENT >>> Connection was lost. Trying to reconnect...");
                closeConnection();
                Thread.sleep(100);
                IsConnected = false;
                while (IsConnected == false)
                    runClient();
                    Thread.sleep(200);
            catch (Exception e)
                DisplayMessage("CLIENT >>> Error trying to Re-Connect...");
        public static void DisplayMessage(final String IncomingSms)
            System.out.println(IncomingSms);
        System.out.printf("Isms: %s", IncomingSms);  ///naah.
        public static String[][] getResponse()
            return Response;
        public static String getResponse(int row, int col)
            return Response[row][col];
    how can i do below using above code
    The program must be able to work in a non-networked mode. In this mode, the server and client must run in the same VM and must perform no networking, must not use loopback networking i.e: no “localhost” or “127.0.0.1”, and must not involve the serialization of any objects when communicating between the client and server components.
    The operating mode is selected using the single command line argument that is permitted.
    imust use a socket connection and define a protocol. networking must be entirely bypassed in the non-network mode.

  • Server Socket Leaks on stopping Java Processes

    I have a strange problem on Windows 2000 Advanced Server with JDK1.5.10. Our application runs on a Tomcat 5.5.12 and is opening 2 server sockets along with Tomcat's own 8080 port. Also we deployed a stand alone application that also opens a server socket. Whenever we stop Tomcat service or our Application service (Windows services) these server sockets are not getting closed. If we use "netstat" to check if any sockets are still open it is NOT showing any sockets.
    But when we use "netstat -a" command it is showing entries like
    TCP    10.40.1.162:8080    10.40.1.162:0  LISTENING
    TCP    10.40.1.162:22222    10.40.1.162:0  LISTENING
    TCP    10.40.1.162:33334    10.40.1.162:0  LISTENINGHere 8080 (tomcat), 22222, 33334 are the ports on which the server sockets are opened earlier. We check in Task Manager but there is no java process running. If we try to restart the same java process it is throwing JVM_Bind exception. If we reboot the box the we are able to restart the services. Similar behaviour we observed sometimes on Linux also. I guess some settings in the OS we need to tweak to fix this issue. Can somebody please help me what are those settings for Windows and Linux platforms which reclaims unused server sockets faster??

    The state is LISTENING not TIME_WAIT. There is a cleanly closure of sockets provided in the code. It happens to Tomcat's own ports also. If you telnet to these sockets from another box, it is connecting and staying instead of "Connection Failed" error. But in Task Manager or "Services.msc" Console no service or process running! One more observation is that there is heavy load of threads and a huge number of clients socktets were interacting with these sockets just before shutdown.

  • Two server sockets on the same machine, one not working.

    Dear forum users.
    I'm currently having a problem with running two server sockets on the same computer.
    It gives no exceptions or anything, just that if i connect with another machine, the last serversocket that started,
    will not accept connections..
    Scenario:
    Computer 1: Main server.
    Computer 1: Game server.
    Computer 2: Client
    Computer 2 connects first to the main server (lets say port 13371)
    Then connects to game server (port 6112).
    Computer 2 failes to connect to the Game server for some reason.
    But if i open a client at Computer 1, connects to main server, and then game server, it
    works fine.
    And if I put computer 2 as a Game server,
    then everything works fine.
    Working scenario:
    Computer 1: Main server.
    Computer 2: Game server
    Computer 2: Client
    Computer 1: Client
    Now, however many that wants to connect to game server, works.
    I have gone through the code 100 times now it feels like. And still dont see why this happends.
    Anyone know if it is "working as intended"? Or just me doing something completely wrong that i cant see myself?
    Sorry for not posting code, its too much code to post.

    Oh, sorry.
    TCPServer:
    protected ServerSocket serverSocket;
    public abstract void processConnection(Socket client);
        public void listen() {
            try {
                report("Listening to clients on port: " + portNumber);
                while (serverSocket != null && acceptConnections) {
                    processConnection(serverSocket.accept());
                    report("Client accepted on serverSocket.");
            } catch (SocketException e) {
                report("TCPServer/listenForClients : SocketException.", e);
            } catch (Exception e) {
                report("TCPServer/listenForClients : Unknown Exception.", e);
            cleanUp();
            report("Stopped listening on port: " + portNumber);
        }MainServer extends the TCPServer:
        public void processConnection(Socket client) {
            try {
                MainServer_Client tmp = new MainServer_Client(client, this);
                synchronized (clients) {
                    clients.add(tmp);
                Thread th = new Thread(tmp);
                th.start();
            } catch (Exception e) {
                report("MainServer/processConnection : Unknown Exception", e);
        }GameServer extends TCPServer
        public void processConnection(Socket client) {
            try {
                client.setTcpNoDelay(true);
                GameServer_ServerClient tmp = new GameServer_ServerClient(client, this);
                synchronized(clients) {
                    clients.add(tmp);
                Thread th = new Thread(tmp);
                th.start();
            } catch(Exception e) {
                report("GameServer_Host/processConnection : Unknown Exception",e);
                e.printStackTrace();
        }Edited by: Lgeee on Apr 30, 2010 2:57 AM

  • Problems reading  an SSL server socket stream using readByte()

    Hi I'm trying to read an SSL server socket stream using readByte(). I need to use readByte() because my program acts an LDAP proxy (receives LDAP messages from an LDAP client then passes them onto an actual LDAP server. It works fine with normal LDAP data streams but once an SSL data stream is introduced, readByte just hangs! Here is my code.....
    help!!! anyone?... anyone?
    1. SSL Socket is first read into  " InputStream input"
    public void     run()
              Authorization     auth = new Authorization();
              try     {
                   InputStream     input     =     client.getInputStream();
                   while     (true)
                   {     StandLdapCommand command;
                        try
                             command = new StandLdapCommand(input);
                             Authorization     t = command.get_auth();
                             if (t != null )
                                  auth = t;
                        catch( SocketException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection closed: " + e );
                             close( e );
                             break;
                        catch( EOFException e )
                        {     // If socket error, drop the connection
                             Message.Info( "Client connection close: " + e );
                             close( e );
                             break;
                        catch( Exception e )
                             //Way too many of these to trace them!
                             Message.Error( "Command not processed due to exception");
                             close( e );
                                            break;
                                            //continue;
                        processor.processBefore(auth,     command);
                                    try
                                      Thread.sleep(40); //yield to other threads
                                    catch(InterruptedException ie) {}
              catch     (Exception e)
                   close(e);
    2 Then data is sent to an intermediate function 
    from this statement in the function above:   command = new StandLdapCommand(input);
         public StandLdapCommand(InputStream     in)     throws IOException
              message     =     LDAPMessage.receive(in);
              analyze();
    Then finally, the read function where it hangs at  "int tag = (int)din.readByte(); "
    public static LDAPMessage receive(InputStream is) throws IOException
        *  LDAP Message Format =
        *      1.  LBER_SEQUENCE                           --  1 byte
        *      2.  Length                                  --  variable length     = 3 + 4 + 5 ....
        *      3.  ID                                      --  variable length
        *      4.  LDAP_REQ_msg                            --  1 byte
        *      5.  Message specific structure              --  variable length
        DataInputStream din = new DataInputStream(is);
           int tag = (int)din.readByte();      // sequence tag// sequence tag

    I suspect you are actually getting an Exception and not tracing the cause properly and then doing a sleep and then getting another Exception. Never ever catch an exception without tracing what it actually is somewhere.
    Also I don't know what the sleep is supposed to be for. You will block in readByte() until something comes in, and that should be enough yielding for anybody. The sleep is just literally a waste of time.

  • Server socket Hangs

    Hi,I am using the server socket in Java to listen on a port on a computer..
    I am using the windows platform
    I use ms vj++6.0
    I am facing a peculiar problem.
    about once in 10 messages received by my server socket,
    The server socket hangs .
    Hangs means it stops responding to the incoming message & so my application
    is unable to take any action.
    I used a port scanner & found that my server port is in a "close_wait"
    state.
    Can someone tell me the reason for this.
    is it a problem with my server or can the client that sends the message be
    also responsible for this type of an error.
    Heres the code for my server
    public server()
    try
    server = new ServerSocket(2156);
    serverthread = new Thread(this);
    serverthread.start();
    catch(Exception e)
    System.out.println("Cannot Start Thread" + e);
    public synchronized void run()
    try
    while(true)
    String line;
    System.out.println("listening for the client");
    fromclient = server.accept();
    System.out.println("client has responded");
    InputStreamReader isr = new
    InputStreamReader(fromclient.getInputStream());
    BufferedReader instream = new BufferedReader(isr);
    PrintWriter ostream = new PrintWriter(new
    BufferedOutputStream(fromclient.getOutputStream()));
    System.out.println("talking to the client\n");
    ostream.println("Hye Client");
    ostream.println("Bye");
    ostream.flush();
    System.out.println("listening to the client \n");
    String temp;
    int count=0;
    String ip="";
    while((line=instream.readLine())!=null)
    System.out.println(line+"\n");
    if (line.equals("Bye"))
    break;
    if (line.equals(""))
    continue;
    else
    System.out.println(line+"\n"); /*Print the line that has come in the
    socket*/
    ostream.close();
    fromclient.close();
    catch(Exception e)
    System.out.println("Cannot listen to the client" + e);
    I hope somebody can help me out .
    Thanx in advance
    Regards
    Sanket Gupta

    You don't seem to properly close the server socket any where. Here why don't you look at this skeleton. This may help you.
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class server
         static boolean listen = true;
         public static void main(String args[])
              try
                   ServerSocket ss = new ServerSocket(2156);
                   do
                        new serverThread(ss.accept()).start();
                   while(listen);
                   ss.close();
              catch(IOException e)
                   System.err.println(e.getMessage());
         public static void shutdown()
              listen = false;
    class serverThread extends Thread
         private Socket client;
         private String input;
         private BufferedReader in;
         private PrintWriter out;
         public serverThread(Socket c)
              client = c;
         public void run()
            try
              in = new BufferedReader(new InputStreamReader(client.getInputStream()));
              out = new PrintWriter(client.getOutputStream(),true);
              input = in.readLine();
              if(input.equals("Hello"))
                   out.println("How are you doing?");
              else if(input.equals("shutdown!"))
                   server.shutdown();
              else
                   out.println("Bad Request!");
              in.close();
              out.close();
              client.close();
            catch(IOException e)
                 System.err.println(e.getMessage());
    }

Maybe you are looking for

  • Set type creation and updation of the structure COMT_PROD_MAT_MAINTAIN_API

    Hello Experts, I've the below scenario, I created new Org dependent Z set type and assigned to a category. And I'm using the API - COM_PRODUCT_GETDETAIL_API to get the details about the material via the export parameter ES_MATERIAL_DATA which has the

  • FI -Follow on Doc-Plant field not updated for Plant to Plant Tfr

    Hi All, For plant to plant stock transfer made with movement type 641- the receiving plant and  supplying plant fields are not getting populated in the debit and credit line items respectively in  the accounting document. In FI the same G/L Account i

  • Creating Private Inner Classes in Separate Files

    I sometimes find myself wanting to use private inner classes to do things, but then moving the classes to separate files and giving them package access just because I don't like having single large files. Is there a way to create private inner classe

  • When ending a successful call, i get a Failed Call message

    When ending a successful incoming call, a message is displayed saying call failed. I think this happens when the other person terminates the call before i do. It's doesn't seem to happen with landlines, but does when a mobile calls me. It seems the i

  • No startup disk recognized during recovery

    Recently my computer malfunctioned and crashed for no reason; it was a seemeingly random crash, my only thought is maybe the computer overheated. I shut down the computer and restarted it. Now all I see is the flashing folder with a question mark. I