I’m working on a general server and a client programs. The problem I’m facing is when I’m in the OnDataReceived in my client and server I don’t know what to do with the data. Ideally it should output the received data into a window but I don’t know if it will be a Form or Console application. So the question is how do I create a general method that can handle both or if that is not possible what should I do instead?
The code I’m working with:
SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
int iRx = theSockId.m_currentSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
Decoder decode = Encoding.Default.GetDecoder();
int charLength = decode.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
String szData = new String(chars);
//Handle Message here
WaitForData();
And the socket packet class:
class SocketPacket
{
public Socket m_currentSocket;
public byte[] dataBuffer = new byte[1024];//Buffer to store the data by the client
public SocketPacket(Socket socket)
{
m_currentSocket = socket;
}
}
PS.
I don’t know if needs to be known but I’m doing asynchronous Client/Server.
Your communication classes shouldn’t care what happens to the data they receive. Instead, they should either make the data available to a class that wants it. One way to do so would be to provide a getData() method, which received data and then returned it to the caller. Even better would be to provide a DataArrived event, which was fired whenever you received data. That way, any number of consumers could listen for data, but your communication code doesn`t have to know which classes are listening or what they plan to do with the data.
EDIT:
A simple example:
In your listener class: