通过套接字传达android和windows

时间:2015-01-05 16:05:23

标签: android .net sockets

我想让我的Android应用程序打开套接字到我的Windows控制台应用程序,他们互相沟通。套接字打开,数据在Windows应用程序中发送和接收,但我的Android应用程序没有收到由Windows发送的答案。我在我的机器人中观察数据包,我看到数据包即将到来,但我不知道为什么我的应用程序没有收到它!

windows app服务器类:

class Server
{
    private TcpListener tcpListener;
    private Thread listenThread;

    public Server()
    {
        Console.WriteLine("\nStarting server...");

        this.tcpListener = new TcpListener(IPAddress.Any, 1234);
        this.listenThread = new Thread(new ThreadStart(ListenForClients));
        this.listenThread.Start();
    }

    private void ListenForClients()
    {
        Console.WriteLine("\nWaiting for clients to connect...");

        this.tcpListener.Start();

        while (true)
        {
            //blocks until a client has connected to the server
            TcpClient client = this.tcpListener.AcceptTcpClient();

            //create a thread to handle communication with connected client
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
        }
    }

    private void HandleClientComm(object client)
    {
        Console.WriteLine("\nIncoming from client...");

        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int bytesRead;

        try
        {
            while (true)
            {
                bytesRead = 0;

                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    break;
                }

                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding();
                Console.WriteLine("\nReceived: \n\n" + encoder.GetString(message, 0, bytesRead));

                //By FMR
                string response = "random responsive: " + new Random().Next(1000).ToString() + "\n";//"\r\n";
                //writeData(clientStream, response);

                byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);

                // Send back a response.
                clientStream.Write(msg, 0, msg.Length);
                clientStream.Flush();

                Console.WriteLine("\nResponed ..." + response);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("\nException while: " + ex.Message);
        }
        tcpClient.Close();
      }
   }

我的android线程:

Thread thread = new Thread(new Runnable() {

@Override
public void run() {
    Socket socket = null;
    ServerSocket serverSocket = null;
    Boolean bRun = true;
    try {
        socket = new Socket(ip, port);

        if(outputStream == null) {
            outputStream = new DataOutputStream(socket.getOutputStream());
        }


        // become server
        serverSocket = new ServerSocket(port);
        Log.i(G.TAG, "before serverSocket.accept");
        socket = serverSocket.accept();
        Log.i(G.TAG, "response recieve: ");

        inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }
    catch (Exception e) {
        try {
            serverSocket.close();
        } catch (IOException e1) {
            Log.e(G.TAG, "serverSocket.close() e: " + e1.getMessage());
        }
        try {
            socket.close();
        } catch (IOException e1) {
            Log.e(G.TAG, "socket.close() e: " + e1.getMessage());
        }
    }
    Log.i(G.TAG, "after start recieve: ");
    while (bRun) {
        try {
            Log.i(G.TAG, "while start: ");
            String message = inputStream.readLine();
            Log.i(G.TAG, "response message: " + message);
            if (message != null) {
                setListMessage(false, message);
            }
        }
        catch (IOException e) {
            bRun = false;
            Log.e(G.TAG, "while bRun e: " + e.getMessage());
        }
    }
}
});
thread.start();

// in another function, my message is sent successfully from android and receive in windows

1 个答案:

答案 0 :(得分:1)

我发现了问题,这一行

socket = serverSocket.accept();

当我评论该行时出现问题,Android应用程序收到了响应!

有人知道为什么吗?