forked from haneytron/simplsockets
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathClientSendMessage.cs
More file actions
72 lines (56 loc) · 2.39 KB
/
ClientSendMessage.cs
File metadata and controls
72 lines (56 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
using System;
using SimplMessage;
using System.Net;
namespace SimplSocketsClient
{
public class ClientSendMessage
{
public void Start()
{
CreateServer();
CreateClient();
}
// Define a class to be send
public class ClassA
{
public int VarInt;
public double VarDouble;
}
void CreateServer()
{
// Create the server
var server = new SimplMessageServer();
// Create a callback for received data of type classA
// (You could also implement this as a lambda function)
server.AddCallBack<ClassA>(ServerReceivedClassACallback);
// Create a callback for received data of type classA with a custom identifier
server.AddCallBack("ObjectOfTypeClassA",ServerReceivedClassACallback);
// Start listening for client connections on loopback end point
server.Listen(new IPEndPoint(IPAddress.Loopback, 5000));
}
void CreateClient()
{
// Create the client
var client = new SimplMessageClient();
// Make the client connect automatically
client.AutoConnect();
// Wait until the connection is actually made
client.WaitForConnection();
// Create an object to send
var objectToSend = new ClassA() { VarInt = 2, VarDouble = 2.5 };
// Send it with an implicit descriptor (which is the class name)
Console.WriteLine($"Client sending received message: {objectToSend.VarDouble}, {objectToSend.VarInt} with implicit descriptor {typeof(ClassA).Name}");
client.Send(objectToSend);
// Send it with a custom descriptor
Console.WriteLine($"Client sending received message: {objectToSend.VarDouble}, {objectToSend.VarInt} with descriptor ObjectOfTypeClassA");
client.Send("ObjectOfTypeClassA",objectToSend);
}
private void ServerReceivedClassACallback(ReceivedMessage receivedMessage)
{
// get data from received message
var receivedObject = receivedMessage.GetContent<ClassA>();
// Notify that the server received data
Console.WriteLine($"Server received message: {receivedObject.VarDouble}, {receivedObject.VarInt}");
}
}
}