Java socket that sends and receives

Asked

Viewed 967 times

2

I’m doing a college project and I’m using an ESP8266 microcontroller. At first, I wanted to create a Socketserver and a Socketclient in Java, which would be able to both receive messages and send to each other, not need to have a multithread connection or anything like that, it could be a connection to a client only, what I need to do is this 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 RFID card presented to Socketserver.

2 - Socketserver receives these characters, and sends a response to the Socketclient, so it can handle my response on the other side accordingly.

However, as it involves Java and C (p/ Arduino programming) on the other side, I would like to make sure that this works first in Java(Server)-Java(Client). I researched several examples, but none of them meet my needs.

1 answer

1

One note: A client-server application in which the two send and receive messages is typically multi thread, has no other output.
First it follows the server code. It is a console application that sends and receives messages to a client. A serverSocket is created on a given port and awaits a connection. After the connection the application becomes multithreaded. The loop inside the constructor reads console strings and sends them to the client. The loop of the run method reads client strings and prints 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();
  }
}

Follow the client code. A client socket is created with the host and the port as parameter. NOTE: The port must be the same 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(); 
  }
}   

Browser other questions tagged

You are not signed in. Login or sign up in order to post.