Javapublic abstract class Session { public static final int BUFFER_SIZE=8192*2; public static final int ALIVE_TIMEOUT = 60000; private Socket mClient=null; public void killSession() { if (mClient != null){ try { this.mClient.close(); } catch (IOException e) { e.printStackTrace(); } } } public void setClientSocket(Socket client) throws IOException{ if(this.mClient!=null){ mClient.close(); } this.mClient=client; mAliveTimer= new Timer("ALIVE_TIMER"); mAliveTimer.schedule(new TimerTask() { public void run() { sendData(new Packets.KeepAlive()); } },ALIVE_TIMEOUT,ALIVE_TIMEOUT); new Thread(new ClientDataRead(),"CLIENT_THREAD").start(); } protected synchronized boolean sendData(byte[] data){ if(mClient!=null){ try{ mClient.getOutputStream().write(data); } catch(Exception ex){ return false; } return true; }else{ return false; } } protected abstract void disconnect(); public class ClientDataRead implements Runnable{ public void run(){ try{ int receivedBytes; byte[] dataBuffer = new byte[BUFFER_SIZE]; while ((receivedBytes = stream.read(dataBuffer, 0, dataBuffer.length)) != -1) { //Тут я обрабатываю данные.... } disconnect(); } catch(Exception ex) { ex.printStackTrace(); mAliveTimer.cancel(); disconnect(); } finally { try { mClient=null; } catch (Exception e) { e.printStackTrace(); } } } }}
C++ (Qt)QThread *th = new QThread; QTcpSocket *sock = new QTcpSocket;sock->moveToThread( th ); Worker *w = new Worker;w->moveToThread( th ); // Подключаем нужные сигналы между сокетом и работалкой.connect( sock, ..., w ... );connect( sock, ..., w ... ); th->start();