Socket in Java that sends and receives

I'm running a college project and I'm using an ESP8266 microcontroller. At first, I wanted to create a SocketServer and a Socketclient in Java, which were able to both receive messages and send to each other, it does not need to have multithreaded connection or anything of the kind, it can be connection to a client only, what I need to do is the following to illustrate the situation:

1-read an RFID card connected to ESP8266, connect to SocketServer and send this string containing the 8 characters of the presented RFID card to the SocketServer.

2-SocketServer receives these characters, and sends a response to the SocketClient, so it manages to treat the other side of my response accordingly.

However, since it involves Java and C (P/ Arduino programming) on the other side, I would like to make sure this works first in Java(Server)-Java(Client). I gave a researched in several examples, but none meets my need.

Author: Matheus Henrique, 2018-05-19

1 answers

A note: a client-server application in which both send and receive messages is typically multi-threaded, has no other output.
First follows the server code. It is a console application that sends and receives messages to a client. A serverSocket is created on a certain port and is waiting for a connection. After connection the application becomes multithreaded. The loop inside the constructor reads strings from the console and sends them to the client. The run method loop reads the strings and print them on the console.

import java.net.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;

class SrvThread extends Thread {
    ServerSocket serverSocket = null;
    Socket socket = null;
    static DataOutputStream ostream = null;
    static int port = 9090;//porta para comunicacao.
    DataInputStream istream  = null;
    String MRcv= "";
    static String MSnd= "";

    SrvThread(){
    try {
        serverSocket = new ServerSocket(port);
        System.out.println("Aguardando conexão...");
        socket = serverSocket.accept();//aguarda conexao com o cliente.
        System.out.println("Conexão Estabelecida.");
        ostream = new DataOutputStream(socket.getOutputStream());
        istream = new DataInputStream(socket.getInputStream());

        this.start();//inicia uma nova thread. O metodo run é executado.

        Scanner console = new Scanner(System.in);
        while(true){
            System.out.println("Mensagem: ");
            String MSnd = console.nextLine(); //le string do console
            ostream.writeUTF(MSnd);//envia string para o cliente.
            ostream.flush();
       }
    } catch(Exception e){
          System.out.println(e);
      }
  }

  public void run(){
      try {
          while(true){
              MRcv = istream.readUTF();//le as strings do cliente
              System.out.println("Remoto: "+MRcv);
          }
      } catch(Exception e) {
          System.out.println(e);
      }
  }

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

Follows the client code. A client socket is created with the host and port as the parameter. Note: the port must be the same as the one used on the server. The rest of the code is similar to the server code.

import java.net.*;
import java.io.*;
import java.util.Scanner;

public class CliThread extends Thread {

    static DataOutputStream ostream = null;
    DataInputStream istream = null;
    static String host = "";
    static int port = 9090;//porta para comunicacao. Deve ser a mesma do servidor.
    Socket socket = null;
    String MRcv= "";
    static String MSnd= "";


    CliThread(){
        try {
            socket = new Socket("localhost", port);//conecta com o servidor.
            System.out.println("Conectado....");
            this.start();//comeca uma nova thread. O metodo run é executado.
            ostream = new DataOutputStream(socket.getOutputStream());
            istream = new DataInputStream(socket.getInputStream());
            Scanner console = new Scanner(System.in);

            while(true){
                System.out.println("Mensagem: ");
                String MSnd = console.nextLine();//le mensagem do console.
                ostream.writeUTF(MSnd);//manda mensagem para o servidor.
                ostream.flush();
            }
        } catch(Exception e) {System.out.println(e);}
  }

  public void run(){
      while (true) {
          try {        
              MRcv = istream.readUTF();//le mensagem do servidor.
              System.out.println("Remoto: " + MRcv);
          } catch(Exception e) {}
      }
  }


  public static void main(String args[]){
      new CliThread(); 
  }
}   
 1
Author: Williamberg Farias, 2018-05-19 13:12:10