This discussion is archived
3 Replies Latest reply: Nov 17, 2008 5:00 PM by EJP RSS

How to Create a Single Backend Socket connectivity in a Server Socket Pgm

807589 Newbie
Currently Being Moderated
Hi Everybody,

I have a written a Server Socket which connects to back end socket and receiving the data and sending back to the front end. But as per my client requirement i need to create only one socket at the back end. But the code I have written is creating new sockets for each request. Is there any way to use the single client socket connection for all the transactions. I have attached the sample code for the reference.

import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class serl implements Runnable

{

ServerSocket serversocket;
Socket clientsoc;
Socket fromclient;
PrintStream streamtoclient;
BufferedReader streamfromclient;

SocketChannel socket_channel=null;
Thread thread;


public serl()

{

try
{

serversocket = new ServerSocket(1001);//create socket
clientsoc = new Socket("10.100.53.145",200);
socket_channel = clientsoc.getChannel();
}
catch(Exception e)
{
System.out.println("Socket could not be created "+e);
}

thread=new Thread(this);
thread.start();

}

public void run()
{

try
{

while(true)
{
     
     PrintStream streamtobackend=null;
     BufferedReader streamfrombackend = null;

fromclient=serversocket.accept();//accept connection fromclient

streamfromclient=new BufferedReader(new InputStreamReader((fromclient.getInputStream())));
//create a input stream for the socket

streamtoclient=new PrintStream(fromclient.getOutputStream());
//create an a output stream for the socket

String str=streamfromclient.readLine();
//read the message sent by client

System.out.println("Output Input From Vtcpd "+str);

streamtobackend.print(str);

streamtobackend = new PrintStream(clientsoc.getOutputStream());
//create an a output stream for the backend socket

streamfrombackend = new BufferedReader(new InputStreamReader(clientsoc.getInputStream()));
//create a input stream for the backend socket
str=streamfrombackend.readLine();

System.out.println("Output From Backend Client"+str);
streamtoclient.println(str);

}//end of while

}

catch(Exception e)

{

System.out.println("Exception "+e);

}

finally

{

try

{

fromclient.close();

}

catch(Exception e)

{

System.out.println("could not close connection "+e);

}

}

}



public static void main(String ar[])

{



new serl();

}





}