简体   繁体   中英

send byte[] data over network stream socket. c#

i want to send string json over networkstream . code at client side

 using (var ns = new NetworkStream(socket))
{
 string json = JsonConvert.SerializeObject(listCfile, Formatting.Indented);
 byte[] jsonbytes = Encoding.UTF8.GetBytes(json);
 byte[] jsonLength = BitConverter.GetBytes(jsonbytes.Length);
 ns.Write(jsonLength, 0, jsonLength.Length);
 ns.Write(jsonbytes, 0, jsonbytes.Length);
}

jsonbytes was byte[988324]

At server side

 using (var ns = new NetworkStream(socket))
 {
 byte[] byDataLength = new byte[4];
ns.Read(byDataLength, 0, 4);
int jsonLength = BitConverter.ToInt32(byDataLength, 0);
byte[] byData = new byte[jsonLength];
ns.Read(byData, 0, jsonLength);
File.WriteAllBytes("E:\\json.txt",byData);
}

byData was byte[988324]

But byData i received isn't same as jsonbytes i sent.

i need some helps.

Update! some times it works. ByData received is same as jsonbytes i sent Some times it doesn't work :(

You can try using raw sockets to send and receive as well as using a memory stream and end-of-packet mechanism for unknown data lengths.

Below is a snippet of methods showing using raw sockets and buffering in a memory-stream till End-Of-Packet is detected.

    protected const int SIZE_RECEIVE_BUFFER = 1024; /// Receive buffer size
    protected const string EOF = "!#~*|"; /// End of packet string
    MemoryStream _msPacket = new MemoryStream(); /// Memory stream holding buffered data packets
    int _delmtPtr = 0; /// Ranking pointer to check for EOF 
    Socket _baseSocket;
    public event EventHandler OnReceived;

    // TODO: -
    // Add methods to connect or accept connections.
    // When data is send to receiver, send with the same EOF defined above.
    //
    //
    public void RegisterToReceive()
    {
        byte[] ReceiveBuffer = new byte[SIZE_RECEIVE_BUFFER];
        _baseSocket.BeginReceive
        (
            ReceiveBuffer,
            0,
            ReceiveBuffer.Length,
            SocketFlags.None,
            new AsyncCallback(onReceiveData),
            ReceiveBuffer
        );
    }
    private void onReceiveData(IAsyncResult async)
    {
        try
        {
            byte[] buffer = (byte[])async.AsyncState;
            int bytesCtr = 0;
            try
            {
                if (_baseSocket != null)
                    bytesCtr = _baseSocket.EndReceive(async);
            }
            catch { }
            if (bytesCtr > 0)
                processReceivedData(buffer, bytesCtr);
            RegisterToReceive();
        }
        catch{ }
    }

    private void processReceivedData(byte[] buffer, int bufferLength)
    {
        byte[] eof = Encoding.UTF8.GetBytes(EOF);
        int packetStart = 0;
        for (int i = 0; i < bufferLength; i++)
        {
            if (buffer[i].Equals(eof[_delmtPtr]))
            {
                _delmtPtr++;
                if (_delmtPtr == eof.Length)
                {
                    var lenToWrite = i - packetStart - (_delmtPtr - 1);
                    byte[] packet = new byte[lenToWrite + (int)_msPacket.Position];

                    if (lenToWrite > 0)
                        _msPacket.Write(buffer, packetStart, lenToWrite);

                    packetStart = i + 1;
                    _msPacket.Position = 0;
                    _msPacket.Read(packet, 0, packet.Length);

                    try
                    {
                        if (OnReceived != null)
                            OnReceived(packet, EventArgs.Empty);
                    }
                    catch { }
                    _msPacket.Position = 0;
                    _delmtPtr = 0;
                }
            }
            else
            { _delmtPtr = 0; }
        }
        if (packetStart < bufferLength)
            _msPacket.Write(buffer, packetStart, bufferLength - packetStart);
        if (_msPacket.Position == 0)
            _msPacket.SetLength(0);
    }

This can receive large length of data and is independent of length by the sender.

The methods above shows how to receive data only, so will have to include other methods for connect, accept, sending-data, etc on raw sockets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM