-
Notifications
You must be signed in to change notification settings - Fork 32
MessageContract
Mathias Cloet edited this page Aug 29, 2019
·
1 revision
A MessageContract is used to send custom data to sockets, you have to implement the IMessageContract interface and bind the contract to a client and server. The MessageContract is identified with the 'MessageHeader'.
public interface IMessageContract
{
/// <summary>
/// Has to be unique, the header is used to match the message with a delegate.
/// </summary>
string MessageHeader { get; set; }
/// <summary>
/// The output of this method will be sent to the matching socket.
/// </summary>
/// <returns></returns>
byte[] SerializeToBytes();
/// <summary>
/// This method will be used to convert the output of <seealso cref="SerializeToBytes"/> to an object of choice.
/// </summary>
/// <param name="objectBytes"></param>
/// <returns></returns>
object DeserializeToObject(byte[] objectBytes);
/// <summary>
/// OnMessageReceived will handle receiving messages.
/// Format = Socket:Client,MessageObject:Header
/// </summary>
event Action<SimpleSocket,IClientInfo, object, string> OnMessageReceived;
/// <summary>
/// This needs to invoke 'OnMessageReceived'
/// </summary>
/// <param name="socket"></param>
/// <param name="client"></param>
/// <param name="message"></param>
/// <param name="header"></param>
void RaiseOnMessageReceived(SimpleSocket socket,IClientInfo client, object message, string header);
}
Example Implementation:
First Create a new message, here I create a new class MessageA which implements IMessageContract and sends a simple text message to the client/server.
public class MessageA: IMessageContract
{
public MessageA(string header)
{
MessageHeader = header;
}
public string MessageHeader { get; set; }
public byte[] SerializeToBytes()
{
return Encoding.UTF8.GetBytes("This is a MessageContract of the object : MessageA");
}
public object DeserializeToObject(byte[] objectBytes)
{
return Encoding.UTF8.GetString(objectBytes);
}
public event Action<SimpleSocket,IClientInfo, object, string> OnMessageReceived;
public void RaiseOnMessageReceived(SimpleSocket socket,IClientInfo client,object message, string header)
{
OnMessageReceived?.Invoke(socket,client, message, header);
}
}
Adding the MessageContract to your socket (Same way for client and server).
//Create an instance of your class.
SimpleSocket socket= new SimpleSocket();
IMessageContract messageAContract = new MessageA("MessageAHeader");
socket.AddMessageContract(messageAContract);
messageAContract.OnMessageReceived += MessageAContractOnOnMessageReceived;
//Event for the added MessageContract
//The clientInfo is only used on the server side, on the client side it will return null;
private static void MessageAContractOnOnMessageReceived(SimpleSocket client,IClientInfo clientInfo, object message, string header)
{
//Do something.
}