Click here to Skip to main content
15,887,241 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is the Sever Code Now i would like to receive data from the client in both numbers and string value.I want to receive both ways in the application.
am receiving in string value but not in numeric values


XML
 TcpListener server = new TcpListener(IPAddress.Any, Port);
Console.Write("Waiting for Client connection... ");

 TcpClient client = server.AcceptTcpClient();
 Console.WriteLine("\nClient Connected....!");

NetworkStream stream = client.GetStream();

byte[] buffer = new byte[client.ReceiveBufferSize];
 int data = stream.Read(buffer, 0, client.ReceiveBufferSize);
 string ch = Encoding.Unicode.GetString(buffer, 0, data);&
Console.WriteLine(String.Format("Received: {0}", ch));
client.close();
Posted

1 solution

you have to find a way to tell your code what you are receiving, like a protocol. In first place Tcp communication is a transport of bytes. these bytes have a meaning. Either they are the characters of a string or some encoded numbers, like 4 bytes make a 32bit integer.
you can set the very first byte of your tcp-Message as a code which tells you what you are getting like:


TcpListener server = new TcpListener(IPAddress.Any, Port);
Console.Write("Waiting for Client connection... ");
 
 TcpClient client = server.AcceptTcpClient();
 Console.WriteLine("\nClient Connected....!");
 
NetworkStream stream = client.GetStream();
 
byte[] buffer = new byte[client.ReceiveBufferSize];
int data = stream.Read(buffer, 0, client.ReceiveBufferSize);
switch (buffer[0]):
{
case 1: //now i am getting text
    string ch = Encoding.Unicode.GetString(buffer, 0, data);
    Console.WriteLine(String.Format("Received string: {0}", ch));
    break;
case 2: //now i am getting numbers
    int i=0;
    for (int x=1;x<5;x++){
        i=i<<8;
        i+=buffer[x];
    }
    Console.WriteLine(String.Format("Received int: {0}", i));
    break;
}
client.close();


of course you can fill an array of ints by repeating that little loop for each int. so you should check in advance how many ints are encoded in that tcp-message. and of course you need to insert the first byte when sending the message.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900