Need to support TCP connection with 4 byte ASCII header,C# I am sending a comman
ID: 3676274 • Letter: N
Question
Need to support TCP connection with 4 byte ASCII header,C#
I am sending a command a user inputs over to a server through IP and port number. I do not need the code for the server side because I am just writing the command to it and then reading its response back to me. I can send everything and read response with code that i have below, however I cannot get it to read it with a 4 byte ASCII header option.
public static void Main(string[] args)
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("172.2.2.2", 8000);
NetworkStream streamToServer = tcpclnt.GetStream();
StreamReader reader = new StreamReader(streamToServer);
Console.Write("Enter the string to be transmitted : ");
string command = reader.ReadLine();
Console.WriteLine("Sending {0} to server", command);
StreamWriter sw = new StreamWriter(streamToServer);
sw.Write(command);
sw.Flush();
string response = Read(streamToServer); //calls the Read method that reads the stream and returns back the response with the 4 byte ASCII header
Console.WriteLine("Server: " + response);//prints the response from server
}
This right there sends the data, I am wanting a method that will be called something like this that returns the string from the server. Again it needs to be changed to work with a 4 byte ASCII header, that is what I am stuck on.
public static string Read(NetworkStream stream)
{
this method will need to read the stream and return a string back. I have it all as one now, but will put in a while loop, so I need a method to return the string back so I can print it out in main method.
byte[] bb = new byte[4096];
int k = stm.Read(bb, 0, bb.Length);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
}
Explanation / Answer
Please check the below piece of code, you will be able to understand and get what you are looking for. Let me know if you still have any issue.
Server Code:
Client Code:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.