Carmen F. Carmen F. - 6 months ago 15
Java Question

Connecting client-server Java

How do I connect 2 java classes client-server shown in the link below:

https://systembash.com/a-simple-java-tcp-server-and-tcp-client/

It says i need to compile using TCPserver, I have tried finding the compiling option in my IDE, which is Netbeans, but I cant seem to locate it anywhere. Could I ask for some tips of how to connect those 2 files so that server file responds to client app ?

Answer

First you need start the server (the Serversocket) , which will waiting the client socket to connect.

ServerSocket serverSocket = new ServerSocket(PORT);
Socket socket = serverSocket.accept();
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
try {
      Object object = objectInputStream.readObject();
      System.out.println("read by the server\t" + object);
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
      objectOutputStream.writeObject("this is message by the server");
   }catch(Excetion e) {
    e.printStackTrace();
   }

The serversocket's accept, and the OIS's readObject() method will blocking the thread, so you must start a new thread.

The client will connect when you create the socket object. After that you can send and receive messages on both sides through streams.

// host is the localhost IP
Socket socket = new Socket(host, PORT);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
objectOutputStream.writeObject("this is the message by the client");
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
try {
    System.out.println("read by the client\t" + objectInputStream.readObject());
    }catch(Excetion e) {
    e.printStackTrace();
    }
Comments