forked from microsoft/Windows-appsample-networkhelper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTcpCommunicationChannel.cs
219 lines (191 loc) · 8.02 KB
/
TcpCommunicationChannel.cs
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// ---------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ---------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
namespace P2PHelper
{
public class TcpCommunicationChannel : ICommunicationChannel
{
/// <summary>
/// The default port.
/// This port was chosen randomly in the ephemeral port range.
/// </summary>
private const string TCP_COMMUNICATION_PORT = "56789";
/// <summary>
/// The socket connection to the remote TCP server.
/// </summary>
private StreamSocket _remoteSocket;
/// <summary>
/// The local socket connection that will be listening for TCP messages.
/// </summary>
private StreamSocketListener _localSocket;
/// <summary>
/// The port number that the remote TCP server and local TCP server is listening to.
/// </summary>
public string CommunicationPort { get; set; } = TCP_COMMUNICATION_PORT;
/// <summary>
/// The hostname of the remote TCP server that is listeneing for TCP connections.
/// </summary>
public Windows.Networking.HostName RemoteHostname { get; set; }
/// <summary>
/// An event indicating that a message was received from the remote TCP server.
/// </summary>
public event EventHandler<IMessageReceivedEventArgs> MessageReceived = delegate { };
/// <summary>
/// Serializes the data object and sends it to the connected RemoteSocket.
/// For more information on making an object serializable, see DataContractJsonSerializer.
/// </summary>
public async Task SendRemoteMessageAsync(object data)
{
// Connect to the remote host to ensure that the connection exists.
await ConnectToRemoteAsync();
using (var writer = new DataWriter(_remoteSocket.OutputStream))
{
byte[] serializedData = SerializeData(data);
byte[] serializedDataLength = BitConverter.GetBytes(serializedData.Length);
writer.WriteBytes(serializedDataLength);
writer.WriteBytes(serializedData);
await writer.StoreAsync();
await writer.FlushAsync();
}
// Disconnect from the remote host.
DisconnectFromRemote();
}
/// <summary>
/// Creates a TCP socket and binds to the CommunicationPort.
/// Use the default JsonSerializer if null is passed into the serializer parameter.
/// Returns false if you are already listening.
/// </summary>
public async Task<bool> StartListeningAsync()
{
bool status = false;
if (_localSocket == null)
{
_localSocket = new StreamSocketListener();
_localSocket.ConnectionReceived += LocalSocketConnectionReceived;
await _localSocket.BindServiceNameAsync(CommunicationPort);
status = true;
}
return status;
}
/// <summary>
/// Disposes of the TCP socket and sets it to null. Returns false if
/// you weren't listening.
/// </summary>
public async Task<bool> StopListening()
{
bool status = false;
if (_localSocket != null)
{
await _localSocket.CancelIOAsync();
_localSocket.ConnectionReceived -= LocalSocketConnectionReceived;
_localSocket.Dispose();
_localSocket = null;
status = true;
}
return status;
}
/// <summary>
/// The event handler for when a TCP connection has been received.
/// </summary>
private async void LocalSocketConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
using (var reader = new DataReader(args.Socket.InputStream))
{
reader.InputStreamOptions = InputStreamOptions.None;
//Read the length of the payload that will be received.
byte[] payloadSize = new byte[(uint)BitConverter.GetBytes(0).Length];
await reader.LoadAsync((uint)payloadSize.Length);
reader.ReadBytes(payloadSize);
//Read the payload.
int size = BitConverter.ToInt32(payloadSize, 0);
byte[] payload = new byte[size];
await reader.LoadAsync((uint)size);
reader.ReadBytes(payload);
// Notify subscribers that a message was received.
MessageReceived(this, new TcpMessageReceivedEventArgs { Message = payload });
}
}
/// <summary>
/// Creates a RemoteSocket and establishes a connection to the RemoteHostname on CommunicationPort.
/// </summary>
private async Task ConnectToRemoteAsync()
{
_remoteSocket = _remoteSocket ?? new StreamSocket();
await _remoteSocket.ConnectAsync(RemoteHostname, CommunicationPort);
}
/// <summary>
/// Serializes an object by using DataContractJsonSerializer.
/// </summary>
private byte[] SerializeData(object data)
{
using (var stream = new MemoryStream())
{
new DataContractJsonSerializer(data.GetType()).WriteObject(stream, data);
return stream.ToArray();
}
}
/// <summary>
/// Disposes the RemoteSocket.
/// </summary>
private void DisconnectFromRemote()
{
_remoteSocket.Dispose();
_remoteSocket = null;
}
}
/// <summary>
/// The event args that contain the message.
/// </summary>
public class TcpMessageReceivedEventArgs : EventArgs, IMessageReceivedEventArgs
{
public byte[] Message { get; set; }
/// <summary>
/// Deserializes Message by using the DataContractJsonSerializer.
/// </summary>
void IMessageReceivedEventArgs.GetDeserializedMessage(ref object message)
{
using (var stream = new MemoryStream(Message))
{
message = new DataContractJsonSerializer(message.GetType()).ReadObject(stream);
}
}
/// <summary>
/// Converts the Message to a string.
/// </summary>
public override string ToString()
{
return System.Text.Encoding.ASCII.GetString(Message);
}
}
}