为什么android只在c#tcp socket上接收2896字节?

时间:2014-07-04 02:58:09

标签: android sockets tcp

c#使用tcp socket向Android发送消息:

string data = "my message....";
byte[] msg = Encoding.UTF8.GetBytes(data);
//for example msg Length is 5210 bytes
client.socket.SendBufferSize = 500000;
socket.Send(msg, msg.Length, SocketFlags.None);

Android从c#服务器端接收消息:

    socket = new Socket(ServerIP, ServerPort);
    socket.setReceiveBufferSize(500000);
    isReceive = true;
    receiveThread = new ReceiveThread(socket);
    receiveThread.start();

private class ReceiveThread extends Thread{
private InputStream inStream = null;
ReceiveThread(Socket socket){
inStream = socket.getInputStream();
}
@Override
public void run(){
while(isReceive){
byte[] buffer = new byte[99999];
try {
//only receive 2896 bytes?
int size = inStream.read(buffer);
} catch (IOException e) {
unConnSocket();
}
}
}
}

为什么大小只能接收2896个字节?

2 个答案:

答案 0 :(得分:1)

您的Android代码无法知道C#代码发送的字节数。 inStream.read()仅读取当时套接字上当前可用的字节。您应该让C#代码在发送字符串数据之前发送字符串长度,以便Android代码知道预期的字节数,例如:

string data = "my message....";
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
int dataLen = IPAddress.HostToNetworkOrder(dataBytes.Length);
byte[] dataLenBytes = BitConverter.GetBytes(dataLen);
socket.Send(dataLenBytes);
socket.Send(dataBytes);

private class ReceiveThread extends Thread
{
    private DataInputStream inStream = null;

    ReceiveThread(Socket socket)
    {
        inStream = new DataInputStream(socket.getInputStream());
    }

    @Override
    public void run()
    {
        while (isReceive)
        {
            try
            {
                String s;
                int size = inStream.readInt();
                if (size > 0)
                {
                    byte[] buffer = new byte[size];
                    inStream.readFully(buffer); 
                    s = new String(buffer, "UTF-8");
                }
                else
                    s = "";

                // use s as needed ...
            }
            catch (IOException e)
            {
                unConnSocket();
            }
        }
    }
}

答案 1 :(得分:-1)

因为TCP是字节流协议,并且没有义务一次为您提供多个字节。

你必须循环。

我引用Linux man recv(2)

  

接收电话通常会返回任何可用的数据,最多可达到所要求的金额,而非等待收到所需的全部金额。