Imprimer
Catégorie : Embedded Systems
Affichages : 959

 

 

 

import java.io.*;
import java.net.*;
 
class ServerTCP {
  private ServerSocket sockConn;
  private int id;
  private ServerData data; // the shared object between threads

  public ServerTCP(int port) throws IOException {
    sockConn = new ServerSocket(port);
    data = new ServerData( ... );
    id = 0;
  }
  public void mainLoop() {
    while(true) {
      try {
        Socket sockComm = sockConn.accept();
        id += 1;
        ThreadServer t = new ThreadServer(id, sockComm, data);
        t.start();
      }
      catch(IOException e) { ... }
    }
  }
}

 

import java.io.*;
import java.net.*;
 
public ServerThread extends Thread {
  private Socket sockComm;
  private int id;
  private ServerData data;
  BufferedReader br; PrintStream ps;
  // other attributes
  public ServerThread(int id, Socket sockComm, ServerData) {
    this.id = id;
    this.sockComm = sockComm;
    this.data = data;
    // other attributes initialization
  }
 
  public void run() {
    try {
        // streams instantiation
        requestLoop();
        // close streams
      }
      catch(IOException e) {
        System.out.println("client disconnected");
      }
  }

  public void requestLoop() throws IOException {
      // same as in the basic template
  }

  // methods to process requests, same as in basic template
}