Streaming data through sockets continuously in java

Viewed 5607

I wanted to send/receive continuous stream of data from one endpoint to another(peer2peer) with push and pull 'able asynchronously

So to first solve communication , I started with jax-ws soap binding webservice since it has an endpoint and ws-addressing for push mechanism but it seems to be a lot of overhead (heavy as per the docs and since unfamiliar with ws-*, I haven't implemented it , as I need multiple clients listening to the stream at a later point and the stream is 24/7 I wanted thread manageable sockets).

Then I took jax-rs but it does not include ws-addressing in it.(jax-rs 2.0) I also looked at websockets but it required an app server but I want a jvm supportable code

So, Now I am trying to use basic sockets but the problem I am having is streaming the data through socket at server and client receiving it continuously. It is working for the first read but no further. Secondly, how can I make it asynchronous?

public class sSocket {  
public static void main(String args[]) throws IOException{  
    int i = 15000;
    ServerSocket ss;
    Socket socket = null;
    ss = new ServerSocket(i);        
    try
    {
        socket = ss.accept();
        socket.setKeepAlive(true);          

           int iii = 0;            
               System.out.println("New connection accepted " +  socket.getInetAddress() + ":" + socket.getPort());   
               BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
               BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

           while(iii<9)
           {
               Thread.sleep(2000);
               output.write("good" + iii + "\n");
               //System.out.print(input.readLine().toString());
               output.flush();
               iii++;
           }
               //socket.close();
       }        

    catch(IOException e)
    {
        e.printStackTrace();
    }   
}
}

public class cSocket {  
public static void main(String args[]) throws InterruptedException, IOException{
    Socket client = new Socket("127.0.0.1", 15000);     
try{
    client.setKeepAlive(true);
    DataOutputStream out = new DataOutputStream(client.getOutputStream());
    out.writeBytes("Hi Server! I'm " + client.getLocalSocketAddress() + "\n" );     
     BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
     String s;       
     while(true){
     if((s = input.readLine()) != null)
    {
        System.out.println("Message from Server: " + s);
    }}
     //client.close();
    }
    catch(Exception e){
    e.printStackTrace();
    }
}
}

[toString() unavailable - no suspended threads] I see this halting the code in eclipse. The problem seems to be essentially rooted in the input.readLine() in client: error is connection reset : which I assume is because readLine() has reached "EOF"

1 Answers
Related