Couldn’t find this on stackoverflow and I did have an example of it which I’d written several months ago, but can’t find that either now.
Basically I’m sending byte[] from client to server, displaying it in server window, then planning to act on the data within. The data which I’m receiving, however, is not being cleaned each time, example:
I send “ABCDEF”
Server displays “ABCDEF”
I send “GHI”
Server displays “GHIDEF”
I think you can see where I’m coming from, I just need a method of cleaning the byte[] array, for this side of things.
The next step then would be to only read the bytes which I intend to use, so at the minute although I’m only using X amount of the data, I am actually receiving a LOT more data than I need to, and I need to now dispose of the extra data at the end.
Can anyone advise of how I can go about this?
My codes are below.
Client:
static void Main(string[] args)
{
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
Console.WriteLine("Welcome to Josh's humble server.");
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 2000);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(100);
Socket clientSock = sock.Accept();
byte[] mabytes = encoding.GetBytes("Test");
clientSock.Send(mabytes);
Console.WriteLine("Hmmm, data sent!");
Console.ReadLine();
Console.WriteLine(encoding.GetString(mabytes));
Console.ReadLine();
byte[] buffer = encoding.GetBytes("server message");
while (true)
{
clientSock.Receive(buffer);
Console.WriteLine(encoding.GetString(buffer));
}
}
catch (Exception ex)
{
Console.WriteLine(Convert.ToString(ex));
Console.ReadLine();
}
}
Server:
static void Main(string[] args)
{
ASCIIEncoding encoding = new ASCIIEncoding();
IPAddress ip = IPAddress.Parse("127.0.0.1");
Console.WriteLine("Welcome to Josh's humble client.");
Console.ReadLine();
IPEndPoint ipEnd = new IPEndPoint(ip, 2000);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Connect(ipEnd);
while (true)
{
Console.WriteLine("Please enter a message:\n");
byte[] mabyte = encoding.GetBytes(Console.ReadLine());
sock.Send(mabyte);
Console.WriteLine("Sent Data");
}
}
Thanks in advance
You use
clientSock.Receive(buffer);to get data but never check the return value. It may read smaller then the length of buffer. A more correct way can be:Also using
byte[] buffer = encoding.GetBytes("server message");to allocate bytes is not a good way.Use something like
byte[] buffer = new byte[1024*N];–EDIT–
Even this approach can be problematic when a multi-byte char is splitted between consecutive reads.
A better way can be using a TcpClient, wrapping its stream by
new StreamReader(tcpClient.GetStream())and read line by line