problem with socket

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rajbala
    New Member
    • Oct 2006
    • 58

    problem with socket

    hi all,
    this is my program ...... By this need to change my port again and again .....

    will you help me to proper closing of socket......

    code:

    <%!
    ServerSocket MyServer;
    Socket Mysocket;
    File file = new File("file.txt" );
    FileInputStream fis = null;
    BufferedInputSt ream bis = null;
    DataInputStream dis = null;
    DataOutputStrea m dos=null;
    %>

    <%
    int port = Integer.parseIn t(request.getPa rameter("port1" ));
    try{
    MyServer = new ServerSocket(po rt);
    Mysocket = MyServer.accept ();
    fis = new FileInputStream (file);
    bis = new BufferedInputSt ream(fis);
    dis = new DataInputStream (bis);
    dos = new DataOutputStrea m(Mysocket.getO utputStream());
    while (dis.available( ) != 0)
    {
    dos.writeBytes( dis.readLine()) ;
    }


    fis.close();
    bis.close();
    dis.close();
    dos.flush();
    dos.close();
    Mysocket.close( );
    MyServer.close( );
    }
    catch(Exception e)
    {

    System.out.prin tln("Encountere d an error!!!!"+e);
    }

    %>

    End of code:
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    I am not sure what you want do?
    do you require the same ServerSocket to handle multiple clients - if so you have the ServerSocket.ac cept() method in a loop - as clients connect you to create a new Thread to handle communications with the client, e.g.
    Code:
        while ( true ) 
            {
             try {
                  Socket socket = serverSocket.accept(); // Wait for client to connect.
                  // create new Thread to handle client communications
                  new ClientThread(client++, socket).start();
                  }
            catch ( IOException e ) { System.out.println( "Error: " + e );  System.exit( 1 ); }
           }
       }

    Comment

    • rajbala
      New Member
      • Oct 2006
      • 58

      #3
      Originally posted by horace1
      I am not sure what you want do?
      do you require the same ServerSocket to handle multiple clients - if so you have the ServerSocket.ac cept() method in a loop - as clients connect you to create a new Thread to handle communications with the client, e.g.
      Code:
          while ( true ) 
              {
               try {
                    Socket socket = serverSocket.accept(); // Wait for client to connect.
                    // create new Thread to handle client communications
                    new ClientThread(client++, socket).start();
                    }
              catch ( IOException e ) { System.out.println( "Error: " + e );  System.exit( 1 ); }
             }
         }

      hi ,
      when i tried the above code it shutdown tomcat totally. I have to restart tomcat. I had put the socket programing in javascript.
      And i dont have multiple clients. I have to send the data to one port as well as receive the data from other port.
      It is working for receiving data as well as giving data to them for once. But my problem is actually I can't able to use same port again once i had used for transfer data. I had to change the port number again for further trasfer of data.

      thanQ
      -raju

      Comment

      • horace1
        Recognized Expert Top Contributor
        • Nov 2006
        • 1510

        #4
        Originally posted by rajbala
        hi ,
        when i tried the above code it shutdown tomcat totally. I have to restart tomcat. I had put the socket programing in javascript.
        And i dont have multiple clients. I have to send the data to one port as well as receive the data from other port.
        It is working for receiving data as well as giving data to them for once. But my problem is actually I can't able to use same port again once i had used for transfer data. I had to change the port number again for further trasfer of data.

        thanQ
        -raju
        very strange you cannot use the same port.
        I put one of my single threaded TCP servers into a loop. It opened a ServerSocket, accepted a client, talked and then closed the ServerSocket. It then looped back and opened the ServerSocket again using the same port number, etc etc. No problem!

        Is it a Tomcat/Javascript problem?

        Comment

        • maverick19
          New Member
          • Nov 2006
          • 25

          #5
          The code that horace gave has be started separately in a different thread
          because it goes into infinite loop waiting for request at the specified port.
          if you call it from jsp it will hang.

          and clean the resources in the finally block

          Comment

          • rajbala
            New Member
            • Oct 2006
            • 58

            #6
            Originally posted by horace1
            very strange you cannot use the same port.
            I put one of my single threaded TCP servers into a loop. It opened a ServerSocket, accepted a client, talked and then closed the ServerSocket. It then looped back and opened the ServerSocket again using the same port number, etc etc. No problem!

            Is it a Tomcat/Javascript problem?
            hi,
            I am using javascript . But for my javascript cod the clients is c program. I dont think it is tomcat/javascript program. If it is case i not sure what is the problem.
            When i tried the same program in java. In that case also i face same problem.
            once i send data to client for next time i need to change port.
            Can you send me client and server programm in which i didn't need to change my ports agin and again.

            TankQ

            -raju

            Comment

            • horace1
              Recognized Expert Top Contributor
              • Nov 2006
              • 1510

              #7
              Originally posted by rajbala
              hi,
              I am using javascript . But for my javascript cod the clients is c program. I dont think it is tomcat/javascript program. If it is case i not sure what is the problem.
              When i tried the same program in java. In that case also i face same problem.
              once i send data to client for next time i need to change port.
              Can you send me client and server programm in which i didn't need to change my ports agin and again.

              TankQ

              -raju
              here is a simple TCP client and server using port 9000

              server
              Code:
              // TCP server which waits for messages from a client - non threaded
              import java.io.*;
              import java.util.*;
              import java.net.*;
              
              public class TCPserver1 
              {
              public static void main(String args[])
              {
                      int receivePort=9000;             // port to receive TCP connections
                       Socket socket=null;
                       while(true)                      // when client closed start again
                          try
                              {
                                System.out.println("TCP server starting: IP address " 
                                     + InetAddress.getLocalHost().toString() + " port " + receivePort );
                                ServerSocket serverSocket = new ServerSocket(receivePort);
                                socket = serverSocket.accept();    // Wait for client to connect.
                                System.out.println("Client connect from IP address " + socket.getInetAddress()
                                                + " port " + socket.getPort());
                                ObjectInputStream br  = new ObjectInputStream( ( socket.getInputStream() ) );
                                ObjectOutputStream pw = new ObjectOutputStream( socket.getOutputStream() );
                                while(true)                       // receiving messages from client
                                  try
                                  {
                                    String code = (String) br.readObject();
                                    System.out.println( "Server received string: '" + code + "'");
                                  }
                                  catch (Exception se) {System.err.println("closing connection"); break;}
                                serverSocket.close();
                              }
                          catch (Exception se) {System.err.println("run() " + se); }
                      }
              }
              client
              Code:
              // TCP client which sends a message to a server 
              
              import java.io.*;
              import java.util.*;
              import java.net.*;
              
              public class TCPclient
              {
              private final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
              
              
              public static void main(String args[])
              {
                 System.out.println("enter message to send to server");
                 String remoteIPaddress="127.0.0.1";
                 int remotePort=9000;
                 try
                     {
                      Socket socket1 = new Socket( remoteIPaddress, remotePort );   
                      ObjectOutputStream objOut = new ObjectOutputStream( socket1.getOutputStream() );
                      System.out.println("Server contacted OK , enter text to send " );
                      while(true)
                          {
                           String s = in.readLine();
                           objOut.writeObject(s);         // send message
                          }  
                      }
                  catch (IOException e) {System.err.println("TCP client error " +  e); }
               }
              
              }

              Comment

              • rajbala
                New Member
                • Oct 2006
                • 58

                #8
                Originally posted by horace1
                here is a simple TCP client and server using port 9000

                server
                Code:
                // TCP server which waits for messages from a client - non threaded
                import java.io.*;
                import java.util.*;
                import java.net.*;
                
                public class TCPserver1 
                {
                public static void main(String args[])
                {
                        int receivePort=9000;             // port to receive TCP connections
                         Socket socket=null;
                         while(true)                      // when client closed start again
                            try
                                {
                                  System.out.println("TCP server starting: IP address " 
                                       + InetAddress.getLocalHost().toString() + " port " + receivePort );
                                  ServerSocket serverSocket = new ServerSocket(receivePort);
                                  socket = serverSocket.accept();    // Wait for client to connect.
                                  System.out.println("Client connect from IP address " + socket.getInetAddress()
                                                  + " port " + socket.getPort());
                                  ObjectInputStream br  = new ObjectInputStream( ( socket.getInputStream() ) );
                                  ObjectOutputStream pw = new ObjectOutputStream( socket.getOutputStream() );
                                  while(true)                       // receiving messages from client
                                    try
                                    {
                                      String code = (String) br.readObject();
                                      System.out.println( "Server received string: '" + code + "'");
                                    }
                                    catch (Exception se) {System.err.println("closing connection"); break;}
                                  serverSocket.close();
                                }
                            catch (Exception se) {System.err.println("run() " + se); }
                        }
                }
                client
                Code:
                // TCP client which sends a message to a server 
                
                import java.io.*;
                import java.util.*;
                import java.net.*;
                
                public class TCPclient
                {
                private final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                
                
                public static void main(String args[])
                {
                   System.out.println("enter message to send to server");
                   String remoteIPaddress="127.0.0.1";
                   int remotePort=9000;
                   try
                       {
                        Socket socket1 = new Socket( remoteIPaddress, remotePort );   
                        ObjectOutputStream objOut = new ObjectOutputStream( socket1.getOutputStream() );
                        System.out.println("Server contacted OK , enter text to send " );
                        while(true)
                            {
                             String s = in.readLine();
                             objOut.writeObject(s);         // send message
                            }  
                        }
                    catch (IOException e) {System.err.println("TCP client error " +  e); }
                 }
                
                }

                Hi ,
                ThankQ for the code.. It's help me lot. I have netbean IDE5.0 .I run this porgram in it. It's working ..
                I want to know when i close communication between the client and server maually by click on close button of output screen and i run for next time It giving message like ..

                --run() java.net.binExc eption :Address already in use ...
                --TCP server starting :localhost.loca ldomain/127.0.0.1 port 3200....

                I mean At first time It trasfer the data properly.If i close the output screen once and use port again it so the run time error.
                Please suggest me what i can do for above program is there any way to shutdown port and how i stop communicating betwwen them.

                ThanQ
                -raju

                Comment

                • horace1
                  Recognized Expert Top Contributor
                  • Nov 2006
                  • 1510

                  #9
                  when you open a ServerSocket with
                  ServerSocket serverSocket = new ServerSocket(90 00);

                  it binds (listens, attaches) to TCP socket 9000 and if another process trys to attach you get a "socket bind error" or "socket already bound" etc

                  if you don't close the program correctly freeing up the socket it can remain bound even though the program has apparently stopped. Often Java processes are still running and one has to use the Task Manager to kill them. I have even had to reboot machines to free a socket..

                  Make sure when you click on the close button you correctly close all the streams associated with the socket and the socket itself not rely on Java to do it for you

                  Comment

                  • rajbala
                    New Member
                    • Oct 2006
                    • 58

                    #10
                    Originally posted by horace1
                    when you open a ServerSocket with
                    ServerSocket serverSocket = new ServerSocket(90 00);

                    it binds (listens, attaches) to TCP socket 9000 and if another process trys to attach you get a "socket bind error" or "socket already bound" etc

                    if you don't close the program correctly freeing up the socket it can remain bound even though the program has apparently stopped. Often Java processes are still running and one has to use the Task Manager to kill them. I have even had to reboot machines to free a socket..

                    Make sure when you click on the close button you correctly close all the streams associated with the socket and the socket itself not rely on Java to do it for you
                    hi,
                    I dont to close streams. Will you suggest me "How to close streams associated with socket in netbean IDE5.0";
                    A big thanQ for your help.
                    -Raju

                    Comment

                    • horace1
                      Recognized Expert Top Contributor
                      • Nov 2006
                      • 1510

                      #11
                      Originally posted by rajbala
                      hi,
                      I dont to close streams. Will you suggest me "How to close streams associated with socket in netbean IDE5.0";
                      A big thanQ for your help.
                      -Raju
                      If you close the socket the streams should close OK. When I had this problem it was when a parent program started the sever - if the pareent crashed or I killed it, the server was left running and hence next time I ran the parent it could not start the server because the socket was already bound. When you close the javascript does it signal the sever to close down correctly?

                      Comment

                      • rajbala
                        New Member
                        • Oct 2006
                        • 58

                        #12
                        Originally posted by horace1
                        If you close the socket the streams should close OK. When I had this problem it was when a parent program started the sever - if the pareent crashed or I killed it, the server was left running and hence next time I ran the parent it could not start the server because the socket was already bound. When you close the javascript does it signal the sever to close down correctly?
                        hi
                        thankq for your suggestion. Now i got the output .
                        I am able to use the same port if the data is transfer between them in sucessful.
                        If i stopped the port manually or forcebly that port is not useful for next time, by this time i need to change port number.
                        please tell me the solution of above problem...

                        -raju

                        Comment

                        • rajbala
                          New Member
                          • Oct 2006
                          • 58

                          #13
                          Hi,

                          after a socket connection is established between a server and client, client is terminated abnormally.

                          Question:
                          a. will the server socket connection be closed if this happens??
                          b. One way to handle this situation is to set a timeout on the server socket.. but is this required?

                          Thanks
                          -raju

                          Comment

                          • horace1
                            Recognized Expert Top Contributor
                            • Nov 2006
                            • 1510

                            #14
                            Originally posted by rajbala
                            Hi,

                            after a socket connection is established between a server and client, client is terminated abnormally.

                            Question:
                            a. will the server socket connection be closed if this happens??
                            b. One way to handle this situation is to set a timeout on the server socket.. but is this required?

                            Thanks
                            -raju
                            when I have used TCP with Java client and server and the client terminated it causeed an Execption in the server. What happens then depends on the server - a simple single threaded server may just close the ServerSocket and exit e.g.
                            Code:
                                    ServerSocket serverSocket = new ServerSocket(receivePort);
                                    socket = serverSocket.accept();    // Wait for client to connect.
                                    System.out.println("Client connect from IP address " + socket.getInetAddress()
                                                              + " port " + socket.getPort());
                                    ObjectInputStream br  = new ObjectInputStream( ( socket.getInputStream() ) );
                                    ObjectOutputStream pw = new ObjectOutputStream( socket.getOutputStream() );
                                    while(true)                       // receiving messages from client
                                          try
                                              {
                                             String code = (String) br.readObject();
                                             System.out.println( "Server received string: '" + code + "'");
                                              }
                                          catch (Exception se) {System.err.println("closing connection"); break;}
                                    serverSocket.close();   // clients die, close socket
                            an alternative would be to keep the ServerSocket open and loop back to wait for another client connection with accept()

                            Comment

                            Working...