0

我已经为 Socket 连接、发送和返回做了一个服务,有时,它接收到一个信息并阻塞了我的线程,我不知道是什么。一开始,我的线程状态是 RUNNABLE,有一次,它变成了一个循环,我已经 BLOCKED 状态如果有人对我的服务有任何想法或评论,我不确定是否一切都很好,但这是更好的方法我找到了发送和接收套接字消息..谢谢

public class SocketService extends Service{

private final int SERVER_PORT = 6040;
static final int MSG_ID = 0x1337;
private final String TAG = SocketService.class.getSimpleName();

private final IBinder mBinder = new SocketBinder();
private String mClientMsg;

private String serverHost = Fonctions.getTxtIp() ; // server address
private Socket socket; // socket for the connection
private ServerSocket ss = null;
private serverListenerThread listenServerThread; // thread for listening to the server 
private boolean connected = false;    
private PrintWriter out;

private MainActivity main;

public class SocketBinder extends Binder{
    public SocketService getService(){
        return SocketService.this;
    }

}

/**
 * Thread d'Ècoute du port SERVER_PORT
 *
 */

private class serverListenerThread extends Thread implements Runnable{
    private boolean end = false; // Booleen pour finir le thread
    public void run(){
        Log.i(TAG, "Run ServerListenerThread " + SERVER_PORT);
        Socket s = null;
            try {
                ss = new ServerSocket(SERVER_PORT );
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.i(TAG, listenServerThread.getState().toString() );
            while(!end ){                        
                 Message m = new Message();
                    m.what = MSG_ID;
                    Log.i(TAG, listenServerThread.getState().toString() );
                    try {
                        if (s == null)
                            s = ss.accept();
                        BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));                   
                        String st = null;
                        st = input.readLine();
                        mClientMsg = st;
                        if(mClientMsg != null)
                            notifyMsg(mClientMsg);

                Log.i(TAG, "Reception Message : " + mClientMsg);

            }catch(IOException e){
                Log.i(TAG, e.getMessage() );
            }                    
            catch (Exception e) {
                Log.i(TAG, "connection lost" + e.getMessage() );                    
            }

        }
    }

    public void end(){
        Log.w(TAG, "End du Thread!");
        end = true;
    }
}

/***
 * Notifier msg
 */
private void notifyMsg(String msg)
{
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(pIntent);
    mNotificationManager.notify(0, mBuilder.getNotification());
}


/**
 *     Connection au Server pour l'envoi d'un message 
 * @param host
 */
public void start(String host){

    new Thread(new Runnable(){
        public void run() {

            listenServerThread = new serverListenerThread();
            listenServerThread.start();
            if(! connected){
                if(connectServer())
                {
                    Log.i(TAG, "Serverhost Ca Galope");                                   
                    connected = true;
                    Log.i(TAG, listenServerThread.getState().toString() );
                }
            }
                else {
                    Log.i(TAG, "Connected : " + connected);                                   
                    connected = false;
                }                    
        }
    }).start();


}        

/**
 * Connection au Server pour l'envoi d'un message 
 * @return Booleen 
 */
private boolean connectServer(){
    try {

        InetAddress serverAddr = InetAddress.getByName(serverHost);
         socket = new Socket(serverAddr, SERVER_PORT);
       /*  out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true );
            out.println("0|ImHere");
            out.flush();*/
        Log.w(TAG, "Ouverture socket");

    }catch (UnknownHostException e) {
        Log.i(TAG, "Erreur connectServer()" + e.getMessage() );
        e.printStackTrace();
    }
    catch (IOException e) {
        Log.i(TAG, "Erreur connectServer()" + e.getMessage() );
        return false;
    } 
    return true;
}

/**
 * Envoi du message via un PrintWriter
 * @param msg
 */
public void sendMsg(final String msg){        
    new Thread(new Runnable() {
        public void run() {
            Log.i(TAG, "SendMsg : " + msg + connected);                
            if(!connected)
                connectServer();
                try {

                    Log.i(TAG, "print writer");
                            out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true );
                            out.println(msg);
                            out.flush();

                } catch (IOException e) {
                    e.printStackTrace() ;
                    Log.i(TAG, e.getMessage() );
                }    


        }
    }).start();
}


public void setMainActivity(MainActivity main)
{
    this.main = main;
}

public String getMessage(){
    return mClientMsg;
}

public int onStartCommand(Intent intent)
{
    Log.i(TAG, "Start command Service");        
    return Service.START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    Log.i(TAG, "onBind");    
    return this.mBinder;
}

/**
 * Is Connected?
 * @return Booleen 
 */

public boolean isConnected() {
    Log.i(TAG, "isConnected : " + connected);        
    return connected;
}

/**
 * Methode appelÈe ‡ la destruction du service
 */
public void onDestroy()
{
    Log.i(TAG, "Destruction Service");
    super.onDestroy();
}

/**
 * 
 */
public void end(){
    Log.i(TAG, "Deconnexion Server");            
    listenServerThread.end();
    connected = false;
    try {
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

4

0 回答 0