Android套接字失败

时间:2012-11-20 22:10:42

标签: android sockets client

继承我的服务器代码

 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#客户端测试它工作正常,所以我在客户端遇到问题

1 个答案:

答案 0 :(得分: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:如果您想从线程与用户界面进行通信,还需要Handler

问候。