namespace Microshaoft
{
using System;
using System.IO;
using System.Net.Sockets;
public static class SocketDataHelper
{
public static void ReadDataToFixedLengthBytes
(
Socket socket ,
ref byte[] buffer
)
{
int p = 0;
int l = buffer.Length;
while (p < l)
{
int r = socket.Receive
(
buffer
, p
, l - p
, SocketFlags.None
);
p += r;
}
}
public static byte[] ReadDataToFixedLengthBytes
(
int length ,
Socket socket
)
{
int p = 0;
byte[] data = new byte[length];
while (p < length)
{
int r = socket.Receive
(
data
, p
, length - p
, SocketFlags.None
);
p += r;
}
return data;
}
public static byte[] ReadDataToBytes
(
int length,
Socket socket
)
{
byte[] data = new byte[length];
int r = 0;
//SocketError error;
r = socket.Receive
(
data
, 0
, length
, SocketFlags.None
//, out error
);
//if (error != SocketError.Success)
//{
// Console.WriteLine("socket error: {0}", Enum.GetName(typeof(SocketError), error));
// Thread.Sleep(100);
//}
if (r > 0)
{
Array.Resize<byte>(ref data, r);
}
else
{
data = null;
}
return data;
}
public static int ReadDataToBytes
(
Socket socket ,
ref byte[] buffer
)
{
int r = 0;
//SocketError error;
int l = buffer.Length;
r = socket.Receive
(
buffer
, 0
, l
, SocketFlags.None
//, out error
);
//if (error != SocketError.Success)
//{
// Console.WriteLine("socket error: {0}", Enum.GetName(typeof(SocketError), error));
// Thread.Sleep(100);
//}
if (r > 0)
{
Array.Resize<byte>(ref buffer, r);
}
else
{
buffer = null;
}
return r;
}
}
public static class StreamDataHelper
{
private static byte[] ReadDataToBytes(Stream stream)
{
byte[] buffer = new byte[64 * 1024];
MemoryStream ms = new MemoryStream();
int r = 0;
int l = 0;
long position = -1;
if (stream.CanSeek)
{
position = stream.Position;
stream.Position = 0;
}
while (true)
{
r = stream.Read(buffer, 0, buffer.Length);
if (r > 0)
{
l += r;
ms.Write(buffer, 0, r);
}
else
{
break;
}
}
byte[] bytes = new byte[l];
ms.Position = 0;
ms.Read(bytes, 0, (int) l);
ms.Close();
ms = null;
if (position >= 0)
{
stream.Position = position;
}
return bytes;
}
}
}