Reputation: 391
I need to send and receive bytes in from my client to server over NetworkStream. I know how to communicate with strings, but now I need to send and receive bytes.
For example, something like that:
static byte[] Receive(NetworkStream netstr)
{
try
{
byte[] recv = new Byte[256];
int bytes = netstr.Read(recv, 0, recv.Length); //(**This receives the data using the byte method**)
return recv;
}
catch (Exception ex)
{
Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
return null;
}
}
static void Send(NetworkStream netstr, byte[] message)
{
try
{
netstr.Write(message, 0, message.Length);
}
catch (Exception ex)
{
Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
}
}
Server:
private void prejmi_click(object sender, EventArgs e)
{
const string IP = "127.0.0.1";
const ushort PORT = 54321;
TcpListener listener = new TcpListener(IPAddress.Parse(IP), PORT);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
byte[] data = Receive(ns)
}
Client:
private void poslji_Click(object sender, EventArgs e)
{
const string IP = "127.0.0.1";
const ushort PORT = 54321;
TcpClient client = new TcpClient();
client.Connect(IP, PORT);
string test="hello";
byte[] mybyte=Encoding.UTF8.GetBytes(test);
Send(ns,mybyte);
}
But that is not the propper way to do this, because byte[] data on server side will always have length of 256.
Upvotes: 0
Views: 9405
Reputation: 391
Thanks, Jon!
static byte[] Receive(NetworkStream netstr)
{
try
{
// Buffer to store the response bytes.
byte[] recv = new Byte[256];
// Read the first batch of the TcpServer response bytes.
int bytes = netstr.Read(recv, 0, recv.Length); //(**This receives the data using the byte method**)
byte[] a = new byte[bytes];
for(int i = 0; i < bytes; i++)
{
a[i] = recv[i];
}
return a;
}
catch (Exception ex)
{
Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
return null;
}
}
static void Send(NetworkStream netstr, byte[] message)
{
try
{
//byte[] send = Encoding.UTF8.GetBytes(message.ToCharArray(), 0, message.Length);
netstr.Write(message, 0, message.Length);
}
catch (Exception ex)
{
Console.WriteLine("Error!\n" + ex.Message + "\n" + ex.StackTrace);
}
}
Upvotes: 1