keep a Socket Server connection/port open for incoming requests
Hi,
I have a socket server which listens to the incoming messages. The problem is that the socket server terminates the socket connection once it receives a message.
I want this Socket server to keep on running and process all the requests it receives.
Can you please advise which stream shall be kept open for this to be achieved? Below is the code for your reference.
Thanks!
import java.net.*;
import java.io.*;
publicclass SocketServer
{
publicstaticvoid main(String[] args)throws IOException
{
ServerSocket serverSocket =null;
String result =null;
SocketServer sockServer =new SocketServer();
try
{
serverSocket =new ServerSocket(4444);
}
catch (IOException e)
{
System.exit(1);
}
Socket clientSocket =null;
try
{
clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(30000);
}
catch (IOException e)
{
System.exit(1);
}
PrintWriter out =new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader in =new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
inputLine = in.readLine();
if((inputLine ==null) || (inputLine.length() < 1))
{
thrownew IOException("could not read from request stream");
}
else
{
result = sockServer.parseString(inputLine);
out.println("|0|OK|");
}
InputStream is =null;
FileOutputStream fout=null;
BufferedInputStream bufIn =null;
HttpURLConnection con =null;
ByteArrayOutputStream baos =null;
try
{
URL url =new URL("http","10.176.96.64",8080,result);
con = (HttpURLConnection)url.openConnection();
is = con.getInputStream();
bufIn =new BufferedInputStream(is);
fout=new FileOutputStream("Z:\\Clips\\Cache\\"+result);
baos =new ByteArrayOutputStream();
int c = bufIn.read();
while(c != -1)
{
baos.write(c);
c = bufIn.read();
}
baos.writeTo(fout);
}
catch(MalformedURLException mue)
{
System.err.println ("*********In Download File: Invalid URL");
}
catch (IOException ioe)
{
System.err.println ("*********In Download File: I/O Error - " + ioe);
}
finally
{
try
{
baos.close();
bufIn.close();
fout.close();
is.close();
con.disconnect();
}
catch(Exception ex)
{
System.out.println("*********In Download File: Exception Occured: "+ex.toString());
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}

