473,385 Members | 1,379 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

problem with socket

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
13 4517
horace1
1,510 Expert 1GB
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
rajbala
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
horace1
1,510 Expert 1GB
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
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
rajbala
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
horace1
1,510 Expert 1GB
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
rajbala
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
horace1
1,510 Expert 1GB
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
rajbala
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
horace1
1,510 Expert 1GB
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
rajbala
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
rajbala
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
horace1
1,510 Expert 1GB
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

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

Similar topics

0
by: Gonçalo Rodrigues | last post by:
Hi, I have a problem with threads and sockets. I'll try to describe the problem in words with pseudo-code. I've been working on a few classes to make it easier to work with threads. This...
3
by: Thomas Hervé | last post by:
My problem is not really python specific but as I do my implementation in python I hope someone here can help me. I have two programs that talk through a socket. Here is the code : <server>...
4
by: Sa¹o Zagoranski | last post by:
Hi! I'm writing a simple 3D First person shooter game. It is a multiplayer game, where all the players connect to one server.
4
by: yaron | last post by:
Hi, I have a problem when sending data over TCP socket from c# client to java server. the connection established ok, but i can't send data from c# client to java server. it's work ok with...
0
by: Usman | last post by:
Hi I'm having problem with a scenarion where I have a server written in C# and client written in VC6++. Here is the server code that i'm using including the Callback function for handling...
2
by: Changhao | last post by:
Hi, friends, I am implementing a protocol on top of 'asyncore.dispatcher' to send streaming multimedia data over TCP socket. However, I found that the throughput of my current implementation is...
0
by: Ben | last post by:
I modified the logmonitor sdk example so it would work over a network. It works great when the client and server are running on the same PC and have administrator privileges. So I have two...
10
by: Clayton | last post by:
Hi all, I'm trying to develop a server that listens to incoming calls using the asycnhronous methods BeginAccept / EndAccept. I start the server (till this point it is ok) and few seconds later...
0
by: george585 | last post by:
Hello! I am new to network programming, and understand just basics. Using some sample code, and having read documentation, I managed to create a simple app in C# and VB.NET. The application is...
16
by: =?iso-8859-1?q?|-|e|=5F|=5F_B0=DD?= | last post by:
hi all! I got a problem. I declared a SOCKET var in my C program but when i compiled the program it displayed like *--------------------------------------------------------------* *'SOCKET':...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.