C
C#15mo ago
Slycex

✅ Unable to read beyond the end of the stream.

Hello, i have error : Unable to read beyond the end of the stream. at line "short hiheader = reader.ReadInt16();" do you know for what ? thanks
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 5555);

using Socket listener = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

listener.Bind(ipEndPoint);
listener.Listen(100);
Console.WriteLine("Serveur démarré, en attente du client...");

var handler = await listener.AcceptAsync(); // Connexion du client
Console.WriteLine($"Client : \"{ipAddress.MapToIPv4()}\" sur le port : \"{ipEndPoint.Port}\" connecté au serveur.");


MemoryStream memoryStream = new MemoryStream();
var buffer = new byte[1024];

while (true)
{
int byteReceived = await handler.ReceiveAsync(buffer, SocketFlags.None);

if(byteReceived > 0)
{
memoryStream.Write(buffer, 0, byteReceived);
}
else
{
break;
}

BinaryReader reader = new BinaryReader(memoryStream);

- short hiheader = reader.ReadInt16(); // HiHeader (2octets) = packetId (8bits) + lenType (6bits)
short packetId = ((short)(hiheader >> 2));
short lenType = ((short)(hiheader & 3));
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 5555);

using Socket listener = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

listener.Bind(ipEndPoint);
listener.Listen(100);
Console.WriteLine("Serveur démarré, en attente du client...");

var handler = await listener.AcceptAsync(); // Connexion du client
Console.WriteLine($"Client : \"{ipAddress.MapToIPv4()}\" sur le port : \"{ipEndPoint.Port}\" connecté au serveur.");


MemoryStream memoryStream = new MemoryStream();
var buffer = new byte[1024];

while (true)
{
int byteReceived = await handler.ReceiveAsync(buffer, SocketFlags.None);

if(byteReceived > 0)
{
memoryStream.Write(buffer, 0, byteReceived);
}
else
{
break;
}

BinaryReader reader = new BinaryReader(memoryStream);

- short hiheader = reader.ReadInt16(); // HiHeader (2octets) = packetId (8bits) + lenType (6bits)
short packetId = ((short)(hiheader >> 2));
short lenType = ((short)(hiheader & 3));
4 Replies
JakenVeina
JakenVeina15mo ago
do you know for what
for attempting to read beyond the end of the stream, perhaps?
Omnissiah
Omnissiah15mo ago
maybe the stream ended?
Pheubel
Pheubel15mo ago
my guess is that when you are trying to read from the memory stream, you are actually past the data you want to read out. Have a look at the Position property of your memory stream. my guess is that if the position is at 0, then it will work fine.
https://learn.microsoft.com/en-us/dotnet/api/system.io.memorystream?view=net-7.0
MemoryStream Class (System.IO)
Creates a stream whose backing store is memory.
Omnissiah
Omnissiah15mo ago
oh yeah, you probably have to seek to beginning
Want results from more Discord servers?
Add your server