dotnet / WatsonTcp

WatsonTcp is the easiest way to build TCP-based clients and servers in C#.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to identify what the server or client is saying?

SnowdenDev opened this issue · comments

Hello @jchristn, back here again. I'm trying to understand and implement file transfer using WatsonTcp, but I have a problem. The client part, when the appropriate method is invoked, looks like this:

MemoryStream stream = new MemoryStream();
Bitmap screenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(screenshot);
graphics.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, screenshot.Size);
screenshot.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byte[] screenshotBytes;
screenshotBytes = stream.ToArray();
Connection.ClientSocket.Send(screenshotBytes);

The context is that the server requests a screenshot from the client, and the client, upon processing the request, sends the aforementioned code.

So far, so good. But on the server side, how can I identify that what I receive is a screenshot? The common logic I use is as follows:

To send: Connection.ClientSocket.Send("Login|" + Username + "|" + Password);

private async void MessageReceived(object sender, MessageReceivedEventArgs args)
{
if (received.Contains("Login"))
{
string received = Encoding.UTF8.GetString(args.Data);
string[] receivedSplit = received.Split('|');
// Identify the received data with: receivedSplit[0];
}
}

Taking into account the mess I generate in order to identify the meaning of the communication for both the server and the client, I ask for your help in doing this correctly and efficiently. I can't identify the screenshot because it's an array of bytes, and I can't put a string in front of it. I would greatly appreciate your help.

Gu @SnowdenDev nice to hear from you! The approach I would take would be to either A) attach a key-value pair to the message metadata to indicate the message type, or, B) create a single structure that is serialized that includes the data required for any type of message you are sending.

Example of A)

public enum MessageTypeEnum { Hello, Foo, Bar }
Dictionary<string, object> metadata = new Dictionary<string, object>();
metadata.Add("MessageType", MessageTypeEnum.Hello.ToString());
client.Send([data bytes], metadata);

// then on server side, check the metadata to determine how to handle the message data

Example of B)

public class MyMessageType
{
  public MessageTypeEnum MessageType { get; set; } = MessageTypeEnum.Hello;
  public byte[] Data { get; set; } = null;
  public string ...
}
client.Send(JsonConvert.SerializeJson(new MyMessageType(...));

// then on server side, deserialize as MyMessageType and process according to MessageType