2012-11-20 116 views
0

我的繼承人服務器代碼Android的套接字失敗

using System; 
    using System.IO; 
    using System.Net.Sockets; 
    using System.Text; 
    using System.Collections; 
    using System.Threading; 

    public class SynchronousSocketListener 
    { 

    private const int portNum = 4444; 
    private static ArrayList ClientSockets; 
    private static bool ContinueReclaim = true; 
    private static Thread ThreadReclaim; 

    public static void StartListening() 
    { 

     ClientSockets = new ArrayList(); 

     ThreadReclaim = new Thread(new ThreadStart(Reclaim)); 
     ThreadReclaim.Start(); 

     TcpListener listener = new TcpListener(portNum); 
     try 
     { 
      listener.Start(); 

      int TestingCycle = 3; 
      int ClientNbr = 0; 

      // Start listening for connections. 
      Console.WriteLine("Waiting for a connection..."); 
      while (TestingCycle > 0) 
      { 

       TcpClient handler = listener.AcceptTcpClient(); 

       if (handler != null) 
       { 
        Console.WriteLine("Client#{0} accepted!", ++ClientNbr); 
        // An incoming connection needs to be processed. 
        lock (ClientSockets.SyncRoot) 
        { 
         int i = ClientSockets.Add(new ClientHandler(handler)); 
         ((ClientHandler)ClientSockets[i]).Start(); 
         Console.WriteLine("Added sock {0}", i); 
        } 
        --TestingCycle; 
       } 
       else 
        break; 
      } 
      listener.Stop(); 

      ContinueReclaim = false; 
      ThreadReclaim.Join(); 

      foreach (Object Client in ClientSockets) 
      { 
       ((ClientHandler)Client).Stop(); 
      } 

     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.ToString()); 
     } 

     Console.WriteLine("\nHit enter to continue..."); 
     Console.Read(); 

    } 

    private static void Reclaim() 
    { 
     while (ContinueReclaim) 
     { 
      lock (ClientSockets.SyncRoot) 
      { 
       for (int x = ClientSockets.Count - 1; x >= 0; x--) 
       { 
        Object Client = ClientSockets[x]; 
        if (!((ClientHandler)Client).Alive) 
        { 
         ClientSockets.Remove(Client); 
         Console.WriteLine("A client left"); 
        } 
       } 
      } 
      Thread.Sleep(200); 
     } 
    } 


    public static int Main(String[] args) 
    { 
     while (true) 
     { 
      StartListening(); 
     } 
     return 0; 
    } 
} 

class ClientHandler 
{ 

    TcpClient ClientSocket; 
    bool ContinueProcess = false; 
    Thread ClientThread; 

    public ClientHandler(TcpClient ClientSocket) 
    { 
     this.ClientSocket = ClientSocket; 
    } 

    public void Start() 
    { 
     ContinueProcess = true; 
     ClientThread = new Thread(new ThreadStart(Process)); 
     ClientThread.Start(); 
    } 

    private void Process() 
    { 

     // Incoming data from the client. 
     string data = null; 

     // Data buffer for incoming data. 
     byte[] bytes; 

     if (ClientSocket != null) 
     { 
      NetworkStream networkStream = ClientSocket.GetStream(); 
      ClientSocket.ReceiveTimeout = 100; // 1000 miliseconds 

      while (ContinueProcess) 
      { 
       bytes = new byte[ClientSocket.ReceiveBufferSize]; 
       try 
       { 

        int BytesRead = networkStream.Read(bytes, 0, (int)ClientSocket.ReceiveBufferSize); 
        //BytesRead--; 
        if (BytesRead > 0) 
        { 
         Console.WriteLine("Bytes Read - Debugger " + BytesRead); 
         data = Encoding.ASCII.GetString(bytes, 0, BytesRead); 

         // Show the data on the console. 
         Console.WriteLine("Text received : {0}", data); 

         // Echo the data back to the client. 
         byte[] sendBytes = Encoding.ASCII.GetBytes("I rec ya abbas"); 
         networkStream.Write(sendBytes, 0, sendBytes.Length); 

         if (data == "quit") break; 

        } 
       } 
       catch (IOException) { } // Timeout 
       catch (SocketException) 
       { 
        Console.WriteLine("Conection is broken!"); 
        break; 
       } 
       Thread.Sleep(200); 
      } // while (ContinueProcess) 
      networkStream.Close(); 
      ClientSocket.Close(); 
     } 
    } // Process() 

    public void Stop() 
    { 
     ContinueProcess = false; 
     if (ClientThread != null && ClientThread.IsAlive) 
      ClientThread.Join(); 
    } 

    public bool Alive 
    { 
     get 
     { 
      return (ClientThread != null && ClientThread.IsAlive); 
     } 
    } 

} // class ClientHandler 

繼承人我的客戶端代碼:

package com.example.socketclient; 


import android.app.Activity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStreamWriter; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import android.util.Log; 

public class SocketCode extends Activity { 

    public TextView txt; 
    protected SocketCore Conn; 
    public Button b; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 

     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_socket_code); 
     b = (Button)findViewById(R.id.button1); 
     txt = (TextView)findViewById(R.id.textView1); 
     Conn = new SocketCore(this,txt); 
     b.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       Conn.execute(); 

      } 
     }); 






    } 

} 

SocketCore

package com.example.socketclient; 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.Socket; 
import java.net.UnknownHostException; 

import android.app.Activity; 
import android.app.ProgressDialog; 

import android.content.Context; 

import android.os.AsyncTask; 
import android.os.SystemClock; 

import android.os.Bundle; 

import android.util.Log; 

import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.TextView; 


class SocketCore extends AsyncTask<Context, Integer, String> 
{ 
    String text = ""; 
    String finalText = ""; 
    private Context ctx; 
    ProgressDialog dialog; 
    TextView Msg; 
    Socket socket; 
    public SocketCore(Context applicationContext,TextView Change) 
    { 
     // TODO Auto-generated constructor stub 
     ctx = applicationContext; 
     dialog = new ProgressDialog(applicationContext); 
     Msg = Change; 
    } 

    @Override 
    protected String doInBackground(Context... arg0) { 
     // TODO Auto-generated method stub 

     try { 
       InetAddress serverAddr = InetAddress.getByName("192.168.0.150"); 
       Log.d("TCP", "C: Connecting...."); 

       socket = new Socket(serverAddr,4444); 
       // Log.d("TCP", "C: I dunno ..."); 
       String message = "Hello Server .. This is the android client talking to you .. First we are testing Server Crashing"; 

       PrintWriter out = null; 
       BufferedReader in = null; 

       try { 
        Log.d("TCP", "C: Sending: '" + message + "'"); 
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); 
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));     
        //serverReturnString = System.Text.Encoding.ASCII.GetString(response, 0, bytes); 

        out.println("quit"); 
        //out.print("h"); 
        while ((text = in.readLine()) != null) { 
         finalText += text; 
         if(text=="quit") 
         { 
          socket.close(); 
         } 
         Log.d("TCP", "C: Done."+finalText); 
         } 

       // Msg.setText("LOLZ"); 
        Log.d("TCP", "C: Sent."); 



       } catch(Exception e) { 
        Log.e("TCP", "S: Error", e); 
       } /*finally { 
        socket.close(); 
        Log.d("TCP", "S: Closed"); 
       } */ 

      }catch (UnknownHostException e) { 
       // TODO Auto-generated catch block 
       Log.e("TCP", "C: UnknownHostException", e); 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       Log.e("TCP", "C: IOException", e); 
       e.printStackTrace(); 
      }  
      //dialog.setMessage("Recieved: "+finalText); 

     return "COMPLETE"; 
    } 
    protected void onPostExecute(String x) 
    { 
     super.onPostExecute("Finished"); 
     dialog.dismiss(); 
     Msg.setText(finalText); 

    } 
    protected void onPreExecute() 
    {dialog.setTitle("Initializing Connection"); 
    dialog.setMessage("Connecting"); 

     dialog.show(); 
    } 

} 

服務器可以從Android手機閱讀也是Android客戶端從得到消息服務器。 問題在於服務器檢測到連接並開始接收文本和發送答覆。之後,代碼不再接受更多的連接。

注: 我試圖用C#的客戶端能正常工作,所以我在客戶端

+0

你可以多次執行AsynTask ...每次點擊創建新的SocketCore – Selvin

+0

那麼我怎樣才能保持套接字的運行..我不能在主線程寫套接字代碼,這就是爲什麼我去了ASync –

回答

1

不能使用更多然後的AsyncTask有一個問題進行測試。

最簡單的方法是將doInBackground()中的代碼移動到Runnable,然後啓動一個新的Thread,並在每次點擊時運行該代碼。

例子:

private Runnable rSocketCore = new Runnable() { 
    public void run() { 
      //here goes your connection code 
    } 
}; 


    b.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      new Thread(rSocketCore).start(); 
     } 

Note:你也會,如果你想從線程到UI溝通需要一個Handler

問候。