Hi everyone,

I am a little new to Java programming and am doing a simple project. The Problem is that I am able to connect but am not able to send any data. It is a little weird. The server gets the client's IP and the client to is connecting to the correct port yet no data is getting transferred. Perhaps, I am over looking on something, that's why I end up here.

A Brief Description of what I am trying to do:

Monitoring system:
Monitoring system has a pool of threads. Each thread connects to one clustered server. The Job of these threads is to dequeue the request and send them to the clustered servers(something may be wrong here). The Main program gets requests from clients(end user) and queues them.(This part is working well)

Clustered Servers:
These are more like workforce, all they do is get a request and calculate the answer and send them back to the Monitoring System.

End User:
Just a simple application to send the requests and get back answer.

That's all about the project.

Here is a code from Monitoring System.

/** delegates Request to the Clustered server */
public class Delegator implements Runnable {
    int serverID;
    Socket socket = null;
    DataInputStream in = null;
    DataOutputStream out = null;
    FileInputStream fis = null;
    public Delegator(int serverID){
        this.serverID = serverID;
        connectToServer();
    }
    public void run(){
        while(true){
            if(defs.reqQueue[serverID].isEmptyQueue() == false ){
            RequestDetails reqDetails = defs.reqQueue[serverID].peekinto();
            SendandRelay(reqDetails);
                  // record time stamp
            long elaspsedTime = (Calendar.getInstance().getTimeInMillis() -
            reqDetails.TimeStamp.getTimeInMillis()) / 1000;
                    // TODO: Update View State
            }
        }
    }
    public void SendandRelay(RequestDetails reqDetails){
        try{
            out.writeUTF(reqDetails.clientIP );
            out.writeUTF(reqDetails.requestType);
            out.writeUTF(reqDetails.request);
            if(reqDetails.requestType.equalsIgnoreCase("compile")){
                sendFileToServer(reqDetails);
            }
        } catch (IOException ex){}
        relayReply(reqDetails.clientIP);
    }
    private void connectToServer(){
        try{
            socket = new Socket(defs.ServerIP[serverID], defs.clusterPort);
            in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
        } catch (UnknownHostException ex){
        } catch (IOException ex){}
    }
// Below methods are not in context of the problem
    private void sendFileToServer(RequestDetails reqDetails){...}
    private void relayReply(String clientIP){...}

The above class is called by the class RequestHandler.java

...
        for ( int i = 0; i < defs.nServer ; i++){
            delegate[i] = new Delegator(i);
            new Thread(delegate[i]).start();
        }
...

RequestDetails has no methods, except for this constructor method public RequestDetails(String clientIP, String requestType, String request, Calendar TimeStamp) RequestQueue, just handles this in a queue, its working well.

defs contains all the constants and other stuffs as static members.
It contains the server IP, port number to connect, etc


Clustered System:

This part is fairly simple, accepts a request, finds the answer and sends the result back.

class ReqHandler
{
    static DataInputStream in = null;
    static DataOutputStream out = null;
    static ServerSocket server = null;

    public static void main(String[] arg) throws IOException{
        if(arg.length!=0)
            System.out.println("No Parameters please:)");
        try {
            server = new ServerSocket(defs.listeningPort);
            Socket incoming = server.accept();
            in = new DataInputStream(new BufferedInputStream(incoming.getInputStream()));
            out = new DataOutputStream(new BufferedOutputStream(incoming.getOutputStream()));

            while (true) {
//Has not managed to read a single line:(
                String requestID = in.readUTF();
                String requestType = in.readUTF();
                String Request = in.readUTF();
...

help me please.

Dani AI

Generated

nailed the root cause: the monitoring threads were writing into a buffered stream and never forcing those bytes out. A short checklist and a few practical improvements to avoid the same trap in future.

  • Always flush buffered output when you need the peer to receive a logical message now. BufferedOutputStream buffers bytes until full or until you call flush() — calling flush() on your DataOutputStream forces the buffered bytes through the socket. See the docs for BufferedOutputStream for details (BufferedOutputStream docs). Example pattern:
try {
    // write bytes / fields
    out.flush();    // ensure the peer sees the message now
} catch (IOException e) {
    // log and handle reconnect
}
  • Protocol and tools: make sure sender and receiver use the same framing (e.g., DataOutputStream / DataInputStream writeUTF/readUTF pairing) — mismatched encodings/protocols block reads. Consider PrintWriter with autoFlush=true for simple text lines (PrintWriter docs):
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.println(message); // newline triggers auto-flush
  • Avoid common structural problems shown in the thread:

    • Don’t busy-wait on isEmpty() / peek. Use a BlockingQueue and take() so threads block efficiently until work arrives (BlockingQueue docs).
    • Don’t swallow exceptions with empty catch {} blocks — log stack traces and attempt reconnect/cleanup.
    • Only remove a request from the queue after a confirmed successful send/reply, to avoid loss on failure.
    • If you expect many simultaneous clients, accept connections in a loop and hand each socket to a handler thread rather than accepting just once.
  • Performance/latency notes: small writes may be delayed by the Nagle algorithm; call socket.setTcpNoDelay(true) when you need low latency for many small packets (Socket#setTcpNoDelay). Also consider socket timeouts and explicit shutdown/close semantics for robust cleanup.

These changes address the flushing symptom and also harden the design (threading, error handling, and protocol). See the DataOutputStream docs for how its write methods behave when combined with buffers (DataOutputStream docs).

Oh, I am so dumb, I forgot to flush any unsend data from the socket.

It's working like a charm now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.