Imprimer
Catégorie : Embedded Systems
Affichages : 949
1°/ Recalls on TCP socket & client/server
 

 

 


/ TCP socket classes in Java
 

 

 

3°/ What about IoT ?

 

4°/ Basic example

This example is a simple echo client/server (i.e. server sends back the client message)

MyServer.java :

import java.io.*;
import java.net.*;
 
class MyServer  {
 
  public static void main(String []args) {
 
    ServerSocket sockConn = null; // connection waiting socketde connexion
    Socket sockComm = null; // communication socket
    int port = -1;
    PrintStream ps;
    BufferedReader br;
    try {
        port = Integer.parseInt(args[0]);
        sockConn = new ServerSocket(port);
        sockComm = sockConn.accept();
        ps = new PrintStream(sockComm.getOutputStream());
        br = new BufferedReader(new InputStreamReader(sockComm.getInputStream()));
        String msg = br.readLine(); // reception (blocking)
        ps.println(msg); // renvoi
    }
    catch(IOException e) {
        System.err.println("pb socket : "+e.getMessage());
        System.exit(1);
    } 
  }
}

 

MyClient.java :

import java.io.*;
import java.net.*;
 
class MyClient  {
 
  public static void main(String []args) {
 
    Socket sockComm = null; // communication socket
    String ipServ;
    int port = -1;
    PrintStream ps;
    BufferedReader br;
    try {
        ipServ = args[0];
        port = Integer.parseInt(args[1]);
        sockComm = newSocket(ipServ, port);
        ps = new PrintStream(sockComm.getOutputStream());
        br = new BufferedReader(new InputStreamReader(sockComm.getInputStream()));
        System.out.println("I say: "+args[2]);
        ps.println(args[2]); // send
        String msg = br.readLine(); // reception (blocking)
        System.out.println("Server answers: "+msg);
    }
    catch(IOException e) {
        System.err.println("pb socket : "+e.getMessage());
        System.exit(1);
    } 
  }
}
 

Remarks:

 

5°/ A communication protocol using requests

5.1°/ why a protocol

 

 

 

 

 5.2°/ example : a time server
 

 

 5.2.1°/ Using binary data (i.e. classical types of C: byte, short, int, double, ...)

 

 

Remarks :

 5.2.2°/ Using text data

The simplest way is to use lines of text with a "classic" format: an identifier followed by the parameters of the request, all separated by a unique character, generally a space. This is the solution used for the example.


6°/ Classical sketches
cf. dedicated article: client/server templates