Home > Software design >  Client side is not sending message to server Java Socket
Client side is not sending message to server Java Socket

Time:05-11

I am learning about sockets in java, but when I was running a program that sends messages from the client side to server side it doesn't show a message. If I enter some text on the client side it doesn't show up on the server side, but if I type endProcess it stops running. Which means that the message is going through it's just not showing up.

My Client.java code is here:

import java.net.*;
import java.io.*;

public class Client{
  Socket soc;
  DataInputStream dis;
  DataOutputStream dos;

  public Client(){
    try{
      soc = new Socket("(Address)",5000);
      System.out.println("Connection Established");
      dis = new DataInputStream(System.in);
      dos = new DataOutputStream(soc.getOutputStream());
      System.out.println("Streams connected");
    }catch(UnknownHostException u){
      System.out.println(u);
    }catch(IOException i){
      System.out.println(i);
    }

    String line = "";

    while(!line.equals("endConnection")){
      try{
        line = dis.readUTF();
        dos.writeUTF(line);
      }catch(IOException i){
        System.out.println(i);
      }
    }

    try {
        soc.close();
        dis.close();
        dos.close();
    } catch (Exception e) {
        System.out.println(e)    
    }
  }
  public static void main(String[] args) {
      new Client();
  }
}

Here is my Server.java code:

import java.net.*;
import java.io.*;

public class Server {
    ServerSocket serSoc;
    Socket soc;
    DataInputStream dis;

    public Server(){
        try {
            serSoc = new ServerSocket(5000);

            System.out.println("Server Online");

            soc = serSoc.accept();
            System.out.println("Client Connected");

            dis = new DataInputStream(new BufferedInputStream(soc.getInputStream()));
        
            String line = "";
            System.out.println("Waiting for input...");
            while(!line.equals("endConnection")){
                line = dis.readUTF();
                System.out.println(line);
            }
            System.out.println("Client disconnected");

            soc.close();
            dis.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        

    }
    public static void main(String[] args) {
        new Server();
    }
}

CodePudding user response:

There are many problems here.

Duplex protocol issues

line = dis.readUTF();
dos.writeUTF(line);

This isn't going to work; The dis.readUTF() line is going to block (freeze) until a line is read. The problem is, sometimes you have nothing to send in which case you want to read, and something you have nothing to read in which case you want to send. In practice you need to redesign this entirely; you need 2 threads. At which point you get into the issues of multicore, needing synchronization primitives and/or java.util.concurrent classes for all data that is shared between the 2 threads.

Alternatively, adopt a model that is strictly push or pull (where at any given time both parties already know who can send, and if the other party wants to send they simply cannot. For example, every party sends a simply 'NOTHING TO DO' message every second, trading places every time. This is quite an inefficient algorithm, of course. But could be written without involving multiple threads.

Flush and close issues

dos.writeUTF(line);

This doesn't actually send anything, or at least, isn't guaranteed to. To send any data on the internet, it gets wrapped in a packet which has lots of overhead. So, things are buffered until there's a full packet to send. Which means that line doesn't do anything. It just fills a buffer, no packets go out. You first need to close or flush. dos.flush() would help maybe. This is a big problem, because later you do:

soc.close();
dis.close();
dos.close();

You first close the socket, which, well, closes the socket. You then close the streams, which will also send anything that's still stuck in a buffer, except, that will fail, because the socket is already closed. In other words, the line you .writeUTF()-ed? It never gets there. You first shove it in a buffer, then you close the socket, then you send the buffer which won't work as the socket is already closed.

Broken error handling

} catch (Exception e) {
  System.out.println(e);
}

Horrible. Don't do this. Your code reacts to any problem by printing something and just keeping right on going. That means if anything goes wrong, the client will start spamming an endless cavalcade of exception traces and locking up the system with any luck. You want the code to stop running when problems occur. Easiest way, by far, is to just stick throws IOException on your constructor and main method, which is allowed. Distant second best option is to configure your 'eh whatever' catch blocks as throw new RuntimeException("unhandled", e); instead of e.printStackTrace().

What you do (System.out.println(e);) is even worse - you are tossing away extremely useful information such as the stack trace and causal chain.

  • Related