I'm trying to communicate with a server over TCP/IP protocol. Here is my method:
private bool SendTcpRequest<T>(T request, Settings settings)
{
try
{
TcpClient client = new TcpClient(settings.Url, settings.Port);
byte[] data = null;
if (!string.IsNullOrEmpty(request.ToString()))
data = Encoding.ASCII.GetBytes(request.ToString());
NetworkStream stream = client.GetStream();
if (stream.CanWrite)
stream.Write(data, 0, data.Length);
else
{
return false;
}
if (stream.CanRead)
{
byte[] myReadBuffer = new byte[client.ReceiveBufferSize];
IFormatter formatter = new BinaryFormatter();
do
{
var numberOfBytesRead = stream.Read(myReadBuffer, 0, client.ReceiveBufferSize);
responseMessage = new StringBuilder();
responseMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
}
while (stream.DataAvailable);
}
else
{
return false;
}
stream.Close();
client.Close();
return true;
}
catch (ArgumentNullException e)
{
return false;
}
catch (SocketException e)
{
return false;
}
}
The server will send response like bellow:
<TOPUPRESPONSE>
<RESULT>00</RESULT> // status of the transaction
<RESULTTEXT>transaction successful</RESULTTEXT> //description of the result code
<TERMINALID>69500002</TERMINALID>
<TXID>0803170919092</TXID>
<PRODUCTID>XYZ</PRODUCTID>
</TOPUPRESPONSE>
Now I have a c# class for response, I'm wondering how I can map the network response to my class. I'm pretty new in this, I'm not even sure how my responseMessage will look like? Can anyone give some idea please?
Create a class based on that repose if that's what your working with:
Then just deserialize it to work with the data as a class:
or use a StringReader: