从TCP套接字读取数据而不是获取所有数据

时间:2014-07-23 22:40:06

标签: c# android sockets tcp

我正在研究C#和android客户端/服务器应用程序。

Android正在向C#发送消息,我可以看到它正在发送正确的数据,但是C#并没有收到所有数据。

以下是我在C#中的代码

TcpListener tcpListener = new TcpListener(IPAddress.Any, serverTCPPort);
                tcpListener.Start();

                while (true)
                {
                    tcpClient = tcpListener.AcceptTcpClient();

                    stream = tcpClient.GetStream();
                    reader = new StreamReader(stream);
                    writer = new StreamWriter(stream);
                    writer.NewLine = "\r\n";
                    writer.AutoFlush = true;
                    byte[] serverData = new byte[tcpClient.ReceiveBufferSize];
                    int length = stream.Read(serverData, 0, serverData.Length);
                    string received = Encoding.ASCII.GetString(serverData, 0, length);
}

以下是我通过Android发送数据的方式

f (contactInformation.photoBase64String != null) {
                bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.parse(contactInformation.photoBase64String));

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                byte[] b = baos.toByteArray();
                bitmap64Encoded = Base64.encodeToString(b, Base64.DEFAULT);
            }

            Toast.makeText(context, "Incoming call from " + contactInformation.contactName, Toast.LENGTH_LONG).show();

            XmlSettings xmlSettings = new XmlSettings();
            xmlSettings.setIndent(true);
            XmlWriter xmlWriter = new XmlWriter(xmlSettings);

            xmlWriter.writeStartDocument();
            xmlWriter.writeStartElement("StatusManager");
            xmlWriter.writeElementString("Command", Defines.ServerCommands.IncomingCall.toString());
            xmlWriter.writeStartElement("CallInformation");
            xmlWriter.writeElementString("PhoneNumber", phoneNumber);
            xmlWriter.writeElementString("ContactName", contactInformation.contactName);
            if (contactInformation.photoBase64String != null)
            {
                xmlWriter.writeElementString("PhotoUri", bitmap64Encoded);
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndElement();

            String xml = xmlWriter.returnXmlOutput();

            TCPSender tcpSender = new TCPSender(context, DeviceManagement.servers.get(0), xmlWriter.returnXmlOutput());
            Thread thread = new Thread(tcpSender);
            thread.start();

TCP发件人

@Override
    public void run() {
        Log.d("TCPSender", xml);
        HelperClass helperClass = new HelperClass();
        try
        {
            Socket socket = new Socket(foundServerInformation.ipAddress, foundServerInformation.tcpServerPort);

            OutputStream out = socket.getOutputStream();
            PrintWriter output = new PrintWriter(out);
            output.println(xml);
            output.flush();

我猜数据对于字节数组来说太大了,但我找不到如何确保获取Android发送的所有信息的方法。

感谢您提供的任何帮助

2 个答案:

答案 0 :(得分:2)

很难知道问题出在哪里(我看到你的代码没问题),但是在这里你有一个来自微软应该如何完成的工作示例,也许它会给你一些线索。  

TcpListener server=null;   
try
{
      // Set the TcpListener on port 13000.
      Int32 port = 13000;
      IPAddress localAddr = IPAddress.Parse("127.0.0.1");
      // TcpListener server = new TcpListener(port);
      server = new TcpListener(localAddr, port);

      // Start listening for client requests.
      server.Start();

      // Buffer for reading data
      Byte[] bytes = new Byte[256];
      String data = null;

      // Enter the listening loop.
      while(true) 
      {
        Console.Write("Waiting for a connection... ");

        // Perform a blocking call to accept requests.
        // You could also user server.AcceptSocket() here.
        TcpClient client = server.AcceptTcpClient();            
        Console.WriteLine("Connected!");

        data = null;

        // Get a stream object for reading and writing
        NetworkStream stream = client.GetStream();

        int i;

        // Loop to receive all the data sent by the client.
        while((i = stream.Read(bytes, 0, bytes.Length))!=0) 
        {   
          // Translate data bytes to a ASCII string.
          data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
          Console.WriteLine("Received: {0}", data);

          // Process the data sent by the client.
          data = data.ToUpper();

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

          // Send back a response.
          stream.Write(msg, 0, msg.Length);
          Console.WriteLine("Sent: {0}", data);            
        }

        // Shutdown and end connection
        client.Close();
      }
    }
    catch(SocketException e)
    {
      Console.WriteLine("SocketException: {0}", e);
    }
    finally
    {
       // Stop listening for new clients.
       server.Stop();
    }


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

答案 1 :(得分:0)

我终于设法让它工作了,这与使用SendReceiveBuffer有关,我试过但是没有用但现在它这样做我想我错过了一些东西。

以下是我用来接收所有数据的代码

TcpListener tcpListener = new TcpListener(IPAddress.Any, serverTCPPort);
                tcpListener.Start();
                string received = "";
                while (true)
                {
                    tcpClient = tcpListener.AcceptTcpClient();

                    stream = tcpClient.GetStream();
                    reader = new StreamReader(stream);
                    writer = new StreamWriter(stream);
                    writer.NewLine = "\r\n";
                    writer.AutoFlush = true;
                    byte[] bytes = new byte[tcpClient.SendBufferSize];
                    int recv = 0;
                    while (true)
                    {
                        recv = stream.Read(bytes, 0, tcpClient.SendBufferSize);
                        received += System.Text.Encoding.ASCII.GetString(bytes, 0, recv);

                        if (received.EndsWith("\n\n"))
                        {
                            break;
                        }
                    }
}

感谢大家的帮助