发送base64字符串槽插座并没有完全到达

时间:2016-09-17 16:27:38

标签: c# sockets tcp tcpclient networkstream

在我的应用程序中,我想实现配置文件图片,所以我开始使用标准图片,我将其转换为字节数组,然后转换为base64字符串,但是当客户端从服务器请求字符串时它不会完全到达,服务器从数据库中读取整个字符串并将其发送到客户端,客户端只接收字符串的一部分,这是字符串(必须使用pastebin):http://pastebin.com/ZmHhsZgG这是客户端收到的字符串:iVBORw0KGgoAAAANSUhEUgAAAEA 这就是服务器从数据库中获取它的方式:

public string GetPP(string user)
    {
        CONN = new MySqlConnection();
        CONN.ConnectionString = Config.CONNSTRING;
        string query = "select * from members where username='" + user + "'";
        try
        {
            CONN.Open();
            COMMAND = new MySqlCommand(query, CONN);
            READER = COMMAND.ExecuteReader();
            string p = null;
            while (READER.Read())
            {
                 return p = READER.GetString("profilepic");
            }
            return p;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return "";
        }
        finally
        {
            CONN.Dispose();
        }
    }

然后发送它:

private void Do()
    {
        int requestCount = 0;
        byte[] bytesFrom = new byte[20025];
        string dataFromClient = null;
        Byte[] sendBytes = null;
        string serverResponse = null;
        string rCount = null;
        requestCount = 0;
        Responder.Responder R = new Responder.Responder();
        while ((true))
        {
            try
            {
                byte[] buffer = new byte[4];
                requestCount = requestCount + 1;
                NetworkStream networkStream = clientSocket.GetStream();
                buffer = new byte[4];
                int readBytes = networkStream.Read(buffer, 0, 4);
                if (readBytes == 0)
                    break;
                int MessageSize = BitConverter.ToInt32(buffer, 0);
                byte[] bufferreader = new byte[MessageSize];
                readBytes = networkStream.Read(bufferreader, 0, MessageSize);
                if (readBytes == 0)
                    break;
                dataFromClient = Encoding.ASCII.GetString(bufferreader);
                rCount = Convert.ToString(requestCount);
                byte[] outbuffer = new byte[4];
                serverResponse = R.Respond(dataFromClient);
                sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                outbuffer = new byte[4];
                outbuffer = BitConverter.GetBytes(sendBytes.Length);
                networkStream.Write(buffer, 0, 4);
                networkStream.Flush();
                networkStream.Write(sendBytes, 0, sendBytes.Length);
                networkStream.Flush();
            }
            catch (Exception ex)
            {
                Console.WriteLine(" >> " + ex.ToString());
            }
        }
        Console.WriteLine("User Server >> " + "Client No:" + Convert.ToString(clNo) + " Stopped!");
    }

客户收到:

            byte[] inbuffer = new byte[4];
            buffer = new byte[4];
            int readBytes = serverStream.Read(buffer, 0, 4);
            int MessageSize = BitConverter.ToInt32(buffer, 0);
            Console.WriteLine(Convert.ToString(MessageSize));
            byte[] bufferreader = new byte[MessageSize];
            readBytes = serverStream.Read(bufferreader, 0, MessageSize);
            string dataFromServer = Encoding.ASCII.GetString(bufferreader);
            if (dataFromServer.Contains("reauth"))
            {
                MessageBox.Show("Session Expired! Please Re-authenticate..");
                this.Close();
            }
            else
            {
                richTextBox1.Text = dataFromServer; //used to see what it receives
                MemoryStream mStream = new MemoryStream();
                byte[] pData = Convert.FromBase64String(dataFromServer);
                mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
                Bitmap bm = new Bitmap(mStream, false);
                mStream.Dispose();
                pictureBox1.Image = bm;
            }
            clientSocket.Close();

提前致谢

2 个答案:

答案 0 :(得分:1)

我认为数据没有被完全读取,因为“'缓冲区'作为长度指示符发送的变量未初始化为更新值。我想你想发送的是:

serverResponse = R.Respond(dataFromClient);
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
outbuffer = new byte[4];
outbuffer = BitConverter.GetBytes(sendBytes.Length);
**networkStream.Write(outbuffer , 0, 4);**
networkStream.Flush();
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();

答案 1 :(得分:0)

NetworkStream.Read方法返回成功读取的字节数。如果要读取整个数据,则必须多次读取。您可以尝试以下代码:

private int read(NetworkStream ns, Byte[] data_buffer)
    {
        int result = -1;

        const int kBufferSize = 1024 * 1024;
        Byte[] buffer = new Byte[kBufferSize];
        int read_size = 0;
        int real_read_size = 0;
        int read_length;
        int total_length;

        if (ns != null && data_buffer != null)
        {
            try
            {
                total_length = data_buffer.Length;
                read_size = 0;
                real_read_size = 0;
                read_length = 0;

                while (true)
                {
                    read_size = kBufferSize <= (total_length - read_length) ? kBufferSize : total_length - read_length;
                    //todo:if (ns.CanRead)
                    real_read_size = ns.Read(buffer, 0, read_size);


                    if (real_read_size > 0)
                    {
                        Array.Copy(buffer, 0, data_buffer, read_length, real_read_size);

                        read_length += real_read_size;

                        //Console.WriteLine("net Read " + read_length.ToString() + " byte!");

                        if (read_length >= total_length)
                        {
                            result = 0;
                            break;
                        }
                    }
                    else
                    {
                        Console.WriteLine("net Read 0 byte!");
                        result = -1;
                        break;
                    }
                }



            }
            catch (IOException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {

            }
        }

        return result;
    }