By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,554 Members | 1,146 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,554 IT Pros & Developers. It's quick & easy.

problem with socket

P: 58
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;
BufferedInputStream bis = null;
DataInputStream dis = null;
DataOutputStream dos=null;
%>

<%
int port = Integer.parseInt(request.getParameter("port1"));
try{
MyServer = new ServerSocket(port);
Mysocket = MyServer.accept();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
dos = new DataOutputStream(Mysocket.getOutputStream());
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.println("Encountered an error!!!!"+e);
}

%>

End of code:
Nov 15 '06 #1
Share this Question
Share on Google+
13 Replies


Expert 100+
P: 1,510
I am not sure what you want do?
do you require the same ServerSocket to handle multiple clients - if so you have the ServerSocket.accept() method in a loop - as clients connect you to create a new Thread to handle communications with the client, e.g.
Expand|Select|Wrap|Line Numbers
  1.     while ( true ) 
  2.         {
  3.          try {
  4.               Socket socket = serverSocket.accept(); // Wait for client to connect.
  5.               // create new Thread to handle client communications
  6.               new ClientThread(client++, socket).start();
  7.               }
  8.         catch ( IOException e ) { System.out.println( "Error: " + e );  System.exit( 1 ); }
  9.        }
  10.    }
  11.  
Nov 15 '06 #2

P: 58
I am not sure what you want do?
do you require the same ServerSocket to handle multiple clients - if so you have the ServerSocket.accept() method in a loop - as clients connect you to create a new Thread to handle communications with the client, e.g.
Expand|Select|Wrap|Line Numbers
  1.     while ( true ) 
  2.         {
  3.          try {
  4.               Socket socket = serverSocket.accept(); // Wait for client to connect.
  5.               // create new Thread to handle client communications
  6.               new ClientThread(client++, socket).start();
  7.               }
  8.         catch ( IOException e ) { System.out.println( "Error: " + e );  System.exit( 1 ); }
  9.        }
  10.    }
  11.  

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
Nov 15 '06 #3

Expert 100+
P: 1,510
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?
Nov 15 '06 #4

P: 25
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
Nov 15 '06 #5

P: 58
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
Nov 15 '06 #6

Expert 100+
P: 1,510
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
Expand|Select|Wrap|Line Numbers
  1. // TCP server which waits for messages from a client - non threaded
  2. import java.io.*;
  3. import java.util.*;
  4. import java.net.*;
  5.  
  6. public class TCPserver1 
  7. {
  8. public static void main(String args[])
  9. {
  10.         int receivePort=9000;             // port to receive TCP connections
  11.          Socket socket=null;
  12.          while(true)                      // when client closed start again
  13.             try
  14.                 {
  15.                   System.out.println("TCP server starting: IP address " 
  16.                        + InetAddress.getLocalHost().toString() + " port " + receivePort );
  17.                   ServerSocket serverSocket = new ServerSocket(receivePort);
  18.                   socket = serverSocket.accept();    // Wait for client to connect.
  19.                   System.out.println("Client connect from IP address " + socket.getInetAddress()
  20.                                   + " port " + socket.getPort());
  21.                   ObjectInputStream br  = new ObjectInputStream( ( socket.getInputStream() ) );
  22.                   ObjectOutputStream pw = new ObjectOutputStream( socket.getOutputStream() );
  23.                   while(true)                       // receiving messages from client
  24.                     try
  25.                     {
  26.                       String code = (String) br.readObject();
  27.                       System.out.println( "Server received string: '" + code + "'");
  28.                     }
  29.                     catch (Exception se) {System.err.println("closing connection"); break;}
  30.                   serverSocket.close();
  31.                 }
  32.             catch (Exception se) {System.err.println("run() " + se); }
  33.         }
  34. }
  35.  
client
Expand|Select|Wrap|Line Numbers
  1. // TCP client which sends a message to a server 
  2.  
  3. import java.io.*;
  4. import java.util.*;
  5. import java.net.*;
  6.  
  7. public class TCPclient
  8. {
  9. private final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  10.  
  11.  
  12. public static void main(String args[])
  13. {
  14.    System.out.println("enter message to send to server");
  15.    String remoteIPaddress="127.0.0.1";
  16.    int remotePort=9000;
  17.    try
  18.        {
  19.         Socket socket1 = new Socket( remoteIPaddress, remotePort );   
  20.         ObjectOutputStream objOut = new ObjectOutputStream( socket1.getOutputStream() );
  21.         System.out.println("Server contacted OK , enter text to send " );
  22.         while(true)
  23.             {
  24.              String s = in.readLine();
  25.              objOut.writeObject(s);         // send message
  26.             }  
  27.         }
  28.     catch (IOException e) {System.err.println("TCP client error " +  e); }
  29.  }
  30.  
  31. }
  32.  
Nov 15 '06 #7

P: 58
here is a simple TCP client and server using port 9000

server
Expand|Select|Wrap|Line Numbers
  1. // TCP server which waits for messages from a client - non threaded
  2. import java.io.*;
  3. import java.util.*;
  4. import java.net.*;
  5.  
  6. public class TCPserver1 
  7. {
  8. public static void main(String args[])
  9. {
  10.         int receivePort=9000;             // port to receive TCP connections
  11.          Socket socket=null;
  12.          while(true)                      // when client closed start again
  13.             try
  14.                 {
  15.                   System.out.println("TCP server starting: IP address " 
  16.                        + InetAddress.getLocalHost().toString() + " port " + receivePort );
  17.                   ServerSocket serverSocket = new ServerSocket(receivePort);
  18.                   socket = serverSocket.accept();    // Wait for client to connect.
  19.                   System.out.println("Client connect from IP address " + socket.getInetAddress()
  20.                                   + " port " + socket.getPort());
  21.                   ObjectInputStream br  = new ObjectInputStream( ( socket.getInputStream() ) );
  22.                   ObjectOutputStream pw = new ObjectOutputStream( socket.getOutputStream() );
  23.                   while(true)                       // receiving messages from client
  24.                     try
  25.                     {
  26.                       String code = (String) br.readObject();
  27.                       System.out.println( "Server received string: '" + code + "'");
  28.                     }
  29.                     catch (Exception se) {System.err.println("closing connection"); break;}
  30.                   serverSocket.close();
  31.                 }
  32.             catch (Exception se) {System.err.println("run() " + se); }
  33.         }
  34. }
  35.  
client
Expand|Select|Wrap|Line Numbers
  1. // TCP client which sends a message to a server 
  2.  
  3. import java.io.*;
  4. import java.util.*;
  5. import java.net.*;
  6.  
  7. public class TCPclient
  8. {
  9. private final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  10.  
  11.  
  12. public static void main(String args[])
  13. {
  14.    System.out.println("enter message to send to server");
  15.    String remoteIPaddress="127.0.0.1";
  16.    int remotePort=9000;
  17.    try
  18.        {
  19.         Socket socket1 = new Socket( remoteIPaddress, remotePort );   
  20.         ObjectOutputStream objOut = new ObjectOutputStream( socket1.getOutputStream() );
  21.         System.out.println("Server contacted OK , enter text to send " );
  22.         while(true)
  23.             {
  24.              String s = in.readLine();
  25.              objOut.writeObject(s);         // send message
  26.             }  
  27.         }
  28.     catch (IOException e) {System.err.println("TCP client error " +  e); }
  29.  }
  30.  
  31. }
  32.  

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.binException :Address already in use ...
--TCP server starting :localhost.localdomain/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
Nov 16 '06 #8

Expert 100+
P: 1,510
when you open a ServerSocket with
ServerSocket serverSocket = new ServerSocket(9000);

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
Nov 16 '06 #9

P: 58
when you open a ServerSocket with
ServerSocket serverSocket = new ServerSocket(9000);

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
Nov 16 '06 #10

Expert 100+
P: 1,510
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?
Nov 16 '06 #11

P: 58
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
Nov 17 '06 #12

P: 58
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
Nov 17 '06 #13

Expert 100+
P: 1,510
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.
Expand|Select|Wrap|Line Numbers
  1.         ServerSocket serverSocket = new ServerSocket(receivePort);
  2.         socket = serverSocket.accept();    // Wait for client to connect.
  3.         System.out.println("Client connect from IP address " + socket.getInetAddress()
  4.                                   + " port " + socket.getPort());
  5.         ObjectInputStream br  = new ObjectInputStream( ( socket.getInputStream() ) );
  6.         ObjectOutputStream pw = new ObjectOutputStream( socket.getOutputStream() );
  7.         while(true)                       // receiving messages from client
  8.               try
  9.                   {
  10.                  String code = (String) br.readObject();
  11.                  System.out.println( "Server received string: '" + code + "'");
  12.                   }
  13.               catch (Exception se) {System.err.println("closing connection"); break;}
  14.         serverSocket.close();   // clients die, close socket
  15.  
an alternative would be to keep the ServerSocket open and loop back to wait for another client connection with accept()
Nov 17 '06 #14

Post your reply

Sign in to post your reply or Sign up for a free account.