allora ecco dei pezzi del mio codice
Allora questa è la parte che serve al Server per restare in ascolto di nuove comunicazioni e per creare nuovi thread quando un nuovo client di connette
codice:
public class InitServer {
private int m_iPortNumber;
private ServerSocket m_oListenSocket;
private Socket m_oWorkingSocket;
public InitServer () {
m_iPortNumber = 0;
m_oListenSocket = null;
}
public void setListenPort(int port_number) {
m_iPortNumber = port_number;
}
/* Inizializza il Socket */
public boolean init() {
if (m_oListenSocket != null) {
System.out.println("init - Socket già inizializzato");
return true;
}
try
{
m_oListenSocket = new ServerSocket(m_iPortNumber);
}
catch (Exception e)
{
System.out.println("init - fallita ServerSocket, port_number=[" + m_iPortNumber + "]: " + e.getMessage());
return false;
}
return true;
}
/* Termina il Socket */
public int end() {
if (m_oListenSocket != null) {
try
{
m_oListenSocket.close();
}
catch (Exception e)
{
System.out.println("end - fallita close del socket: " + e.getMessage());
}
m_oListenSocket = null;
}
return 0;
}
/* Metto in ascolto il Socket */
public int getConnection(int iTimeout) {
if (m_oListenSocket == null) {
System.out.println("getConnection - Socket non inizializzato");
return 3;
}
System.out.println("getConnection - mi metto in ascolto sulla porta " + m_oListenSocket.getLocalPort());
try
{
m_oWorkingSocket = m_oListenSocket.accept();
//System.out.println(m_oWorkingSocket.getReceiveBufferSize());
//m_oWorkingSocket.setSoTimeout(iTimeout);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("getConnection - Connessione Fallita: " + e.getMessage());
//end();
return 2;
}
System.out.println("getConnection - Richiesta accettata da " + m_oWorkingSocket.getInetAddress().getHostAddress() + " sulla porta " + m_oWorkingSocket.getLocalPort());
return 1;
}
public Socket getSocket() {
return m_oWorkingSocket;
}
public void startWorkServer() {
int iTimeout = 5000;
m_iPortNumber = 60000;
Thread oThread;
if (init()) {
do{
int ConnSocket = getConnection(iTimeout);
if (ConnSocket == 1){
// Istanzio la classe che gestisce la comunicazione con il server, gli passo la socket appena avviata e avvio tutto quanto all'interno di una Thread
ThreadServer serverT = new ThreadServer();
serverT.setWorkingSocket(getSocket());
oThread = new Thread(serverT);
oThread.start();
}else if (ConnSocket == 3){
init();
}
} while (true);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
InitServer oTCPServer;
oTCPServer = new InitServer ();
oTCPServer.startWorkServer();
}
}
Questa classe del server invece gestisce la comunicazione con un client dopo la creazione del thread
codice:
public class ThreadServer implements Runnable{
protected Socket m_oWorkingSocket;
private BufferedReader in;
private BufferedWriter out;
private BufferedInputStream BuffIn;
private BufferedOutputStream BuffOut;
private String valueSTR = "";
/* setta il socket in questo Thread */
public void setWorkingSocket(Socket oWS) {
m_oWorkingSocket = oWS;
}
/* controlla l'inizializzazione del Socket */
public int checkSocket(){
if (m_oWorkingSocket == null) {
System.out.println("checkSocket - Socket non inizializzato");
return -1;
}
return 1;
}
/* Termina il socket corrente e chiude la comunicazione con il client */
public int end() {
if (m_oWorkingSocket != null) {
try {
m_oWorkingSocket.close();
} catch (IOException e) {
System.out.println("end - fallita close:" + e.getMessage());
}
m_oWorkingSocket = null;
}
return 0;
}
/* Inizializza il buffer per la lettura e la scrittura */
public void BufferStream() {
try {
BuffIn = new BufferedInputStream(m_oWorkingSocket.getInputStream());
BuffOut = new BufferedOutputStream(m_oWorkingSocket.getOutputStream());
/* comunico al client l'avvenuta connessione */
if (!writeBytes("SERVER OK".getBytes())){
System.out.println("BufferStream - Impossibile al momento instaurare una comunicazione Client/Server");
}
} catch (Exception e) {
System.out.println("BufferStream - Impossibile al momento instaurare una comunicazione Client/Server");
}
}
/* Legge lo stream di byte che riceve sul socket */
public byte[] readBytes_2(int NumByte) {
byte[] abHeaderBuff = new byte[NumByte];
try {
BuffIn.read(abHeaderBuff);
} catch (IOException e) {
}
return abHeaderBuff;
}
/* Invia byte allo stream del socket */
public boolean writeBytes(byte[] abBuffToWrite) {
boolean bResult;
try {
BuffOut.write(abBuffToWrite);
BuffOut.flush();
System.out.println("writeBytes - inviati " + abBuffToWrite.length + " byte del buffer");
bResult = true;
} catch (IOException exc) {
System.out.println("writeBytes - errore nell'invio del buffer");
bResult = false;
}
return bResult;
}
/* Gestisce le richieste del client connesso */
public int manageRequest() throws Exception {
String value = null;
int iResult = 0;
byte[] Buffer;
System.out.println("In attesa di un comando...");
readBytes_2(10);
//controllo se questi 10 byte contengono quello che voglio, se è si allora deve terminare di leggermi la parte restante dello stream stream
return iResult;
}
/* Metodo convenzionale/iniziale del Thread, avviato eseguendo thread.start(); */
public void run() {
int iResult = 0;
System.out.println("startWork: Sessione " + Thread.currentThread().getName() + " inizializzata per il seguente client " + m_oWorkingSocket.getInetAddress().getHostAddress());
if (checkSocket() > 0){
/* Inizializzo il buffer per lo scambio di dati client/server */
BufferStream();
do {
try {
iResult = manageRequest();
} catch (Exception e) {
//e.printStackTrace();
System.out.println("Errore nel gestire la richiesta");
iResult = -1;
}
} while (iResult == 0); //il ciclo termina quando iResult è diverso da 0
}
System.out.println("La connessione con il client " + m_oWorkingSocket.getInetAddress().getHostAddress() + " è stata terminata.");
end();
}
}
in particolare il BufferStream instanzia l'oggetto BufferedInputStream, manageRequest() è la classe che dovrebbe gestirsi l'elaborazione dei comandi che le vengono inviati nello stream.
Dentro
manageRequest()
viene lancianto readBytes_2(10); che resta in attesa di comandi inviati dal client, quando il client invia qualcosa, vengono letti i primi 10 byte e se contengono quello che gli serve allora manageRequest() si va a leggere la parte restante dello stream
grazie mille per l'aiuto che mi stai dando, son un po confuso su questo punto, scusa se in questi ultimi giorni sto tartassando il forum ma sto impazzendo