This is what I am trying to do. I am taking byte data from an incoming socket program. By default, the bytes passed in to be Encoded and appended to my string will be 1500 bytes since this is the size I defined for the bytes array. My question is, I would like to know how to pass in part of the byte array instead of the whole 1500 bytes.
IPAddress localAddr = IPAddress.Parse(args[0]);
System.Console.WriteLine("The local IP is {0}", localAddr);
Int32 port = int.Parse(args[1]);
System.Console.WriteLine("The port is {0}", port);
TcpListener myListener = new TcpListener(localAddr, port);
byte[] bytes = new byte[1500];
string sem = "";
do
{
int flag = 0;
int rec = 1;
Console.Write("Waiting");
myListener.Start();
Socket mySocket = myListener.AcceptSocket();
// receiving the hl7 message
StringBuilder sbb = new StringBuilder();
do{
// bytes = null;
rec = mySocket.Receive(bytes,SocketFlags.None);
// rec = mySocket.Receive(bytes);
Console.WriteLine("rec = {0} ",rec);
for (int i=0; i<bytes.Length; i++)
{
if (bytes[i]==0x1C)
{
flag = 1;
}
}
sbb.Append(Encoding.ASCII.GetString(bytes));
}while (flag == 0);
Firstly, let’s be clear about what the code shown does:
What it doesn’t do is “copy bytes to a string” – not least a string is essentially “char” data (16 bits each), not byte data. If you wanted to treat byte data as char data, it would just-about work for UTF-16 (depending on the endianness), but not ASCII.
Re choosing how much to append:
Either or both may be useful here; however, I don’t think the code does what you think it does; there are easier ways to initialise a StringBuilder