android线程因未知原因而停止

时间:2014-09-25 19:32:55

标签: java c# android multithreading tcp

我正在通过TCP套接字与Android设备 - PC进行通信。我成功地将网络数据包发送到服务器但是当我尝试从服务器获得响应时,线程停止我不知道原因。 Android客户端:

public class ClientThread implements Runnable 
{
    public void run() 
    {
        try 
        {
                Socket socket = new Socket("192.168.1.12", 4444);

                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                out.write(msg);
                out.flush();

                Log.v("Naber", "One");

                InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // get the client message
                String inMsg = bufferedReader.readLine();
                inputStreamReader.close();
                Log.v("Naber", "Two");
                socket.close();

        }
        catch (Exception e)
        {
            Log.v("Hata", e.getMessage());
        }
    }
}

记录详细输出:

09-25 22:25:37.163  15351-15532/com.mytracia.kumanda9 V/Naber﹕ One

我不知道为什么它在这一行上停止了:

String inMsg = bufferedReader.readLine();

使用C#的我的服务器应用程序

static void Main(string[] args)
    {
        TcpListener tcpListener = new TcpListener(IPAddress.Any, 4444);
        while (true)
        {
            tcpListener.Start();
            //Program blocks on Accept() until a client connects.
            Socket soTcp = tcpListener.AcceptSocket();
            Byte[] received = new Byte[1024];
            int bytesReceived = soTcp.Receive(received, received.Length, 0);
            String dataReceived = System.Text.Encoding.ASCII.GetString(received);
            dataReceived = dataReceived.Replace("\0", "");
            Console.WriteLine(dataReceived);
            String returningString = "Naber1";
            Byte[] returningByte = System.Text.Encoding.ASCII.GetBytes(returningString.ToCharArray());
            //Returning a confirmation string back to the client.
            soTcp.Send(returningByte, returningByte.Length, 0);
            tcpListener.Stop();
        }
    }

1 个答案:

答案 0 :(得分:1)

服务器用新行回答? “\ n” 个

  

public String readLine()在API级别1中添加返回下一行   该阅读器提供的文本。一条线由零或表示   更多字符后跟'\ n','\ r',“\ r \ n”或结尾   读者。该字符串不包含换行符序列。

     

返回行的内容,如果没有读取任何字符,则返回null   在读者结束之前。

尝试:

String returningString = "Naber1\n";