1 //------------------------------------------------------------------------------
2 // <copyright file="ClientWebSocket.cs" company="Microsoft">
3 //     Copyright (c) Microsoft Corporation.  All rights reserved.
4 // </copyright>
5 //------------------------------------------------------------------------------
6 
7 namespace System.Net.WebSockets
8 {
9     using System;
10     using System.Diagnostics.CodeAnalysis;
11     using System.Diagnostics.Contracts;
12     using System.Globalization;
13     using System.IO;
14     using System.Net;
15     using System.Runtime.InteropServices;
16     using System.Security.Permissions;
17     using System.Threading;
18     using System.Threading.Tasks;
19 
20     internal sealed class InternalClientWebSocket : WebSocketBase
21     {
22         private readonly SafeHandle m_SessionHandle;
23         private readonly WebSocketProtocolComponent.Property[] m_Properties;
24 
InternalClientWebSocket(Stream innerStream, string subProtocol, int receiveBufferSize, int sendBufferSize, TimeSpan keepAliveInterval, bool useZeroMaskingKey, ArraySegment<byte> internalBuffer)25         public InternalClientWebSocket(Stream innerStream, string subProtocol, int receiveBufferSize, int sendBufferSize,
26             TimeSpan keepAliveInterval, bool useZeroMaskingKey, ArraySegment<byte> internalBuffer)
27             : base(innerStream, subProtocol, keepAliveInterval,
28                 WebSocketBuffer.CreateClientBuffer(internalBuffer, receiveBufferSize, sendBufferSize))
29         {
30             m_Properties = this.InternalBuffer.CreateProperties(useZeroMaskingKey);
31             m_SessionHandle = this.CreateWebSocketHandle();
32 
33             if (m_SessionHandle == null || m_SessionHandle.IsInvalid)
34             {
35                 WebSocketHelpers.ThrowPlatformNotSupportedException_WSPC();
36             }
37 
38             StartKeepAliveTimer();
39         }
40 
41         internal override SafeHandle SessionHandle
42         {
43             get
44             {
45                 Contract.Assert(m_SessionHandle != null, "'m_SessionHandle MUST NOT be NULL.");
46                 return m_SessionHandle;
47             }
48         }
49 
50         [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands",
51             Justification = "Only harmless information (useZeroMaskingKey) is passed from PT code into native code.")]
CreateWebSocketHandle()52         private SafeHandle CreateWebSocketHandle()
53         {
54             Contract.Assert(m_Properties != null, "'m_Properties' MUST NOT be NULL.");
55             SafeWebSocketHandle sessionHandle;
56             WebSocketProtocolComponent.WebSocketCreateClientHandle(m_Properties, out sessionHandle);
57             Contract.Assert(sessionHandle != null, "'sessionHandle MUST NOT be NULL.");
58 
59             return sessionHandle;
60         }
61     }
62 }
63