Imprimer
Catégorie : Embedded Systems
Affichages : 660

1°/ Recalls on TCP socket classes in Java
 
 

2°/ Basic example

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);
    } 
  }
}
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:

 

3°/ A communication protocol using requests

3.1°/ why a protocol

 

 

 

 

 4.2°/ example : a time server
 

 

 

 

Remarks :

 


4°/ Classical sketches
cf. dedicated article.