epn
epn

Reputation: 83

How to continuously sending data to the port(TCP) by using java?

I want to send continuously data to the client whether the client is using the data or not. I tried in below manner :

public class Ser {
public static void main(String[] args) {
    int number,temp;
    try {
        ServerSocket s1 = new ServerSocket(1342);
        Socket clientSocket = s1.accept();

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        number = 0;
        while (number <= 100) {
            Thread.sleep(1000);
            System.out.println("here");
            out.println(number);
            number++;
        }


    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}

But above code is not working. How can I send continuously data to port in windows?

Upvotes: 2

Views: 650

Answers (1)

Stephen C
Stephen C

Reputation: 719386

It is not possible to continuously send data to a client over a Socket if the client is not going to consume (read) the data. (

  • When I say "not possible" ... if a server could send indefinitely without block, then the "pipe" would need to be able to buffer an indefinitely large amount of data. That would be impractical to implement.

  • And there would be huge problems implementing something whereby a client could skip over data without reading it. How would it know when to stop skipping?

You could use datagrams (e.g. UDP) and a DatagramSocket but then you have the reverse problem. The client may not be able to receive all of the data sent.


I note that there was an error in the original version of your question, but I am assuming that it was a simple typo and not present in your actual code.

Upvotes: 1

Related Questions