websocket-server – Blame information for rev 1
?pathlinks?
Rev | Author | Line No. | Line |
---|---|---|---|
1 | office | 1 | using System; |
2 | using System.Collections.Generic; |
||
3 | using System.Linq; |
||
4 | using System.Text; |
||
5 | using System.IO; |
||
6 | using System.Net.Sockets; |
||
7 | |||
8 | namespace WebSockets.Common |
||
9 | { |
||
10 | // see http://tools.ietf.org/html/rfc6455 for specification |
||
11 | // see fragmentation section for sending multi part messages |
||
12 | // EXAMPLE: For a text message sent as three fragments, |
||
13 | // the first fragment would have an opcode of TextFrame and isLastFrame false, |
||
14 | // the second fragment would have an opcode of ContinuationFrame and isLastFrame false, |
||
15 | // the third fragment would have an opcode of ContinuationFrame and isLastFrame true. |
||
16 | |||
17 | public class WebSocketFrameWriter |
||
18 | { |
||
19 | private readonly Stream _stream; |
||
20 | |||
21 | public WebSocketFrameWriter(Stream stream) |
||
22 | { |
||
23 | _stream = stream; |
||
24 | } |
||
25 | |||
26 | public void Write(WebSocketOpCode opCode, byte[] payload, bool isLastFrame) |
||
27 | { |
||
28 | // best to write everything to a memory stream before we push it onto the wire |
||
29 | // not really necessary but I like it this way |
||
30 | using (MemoryStream memoryStream = new MemoryStream()) |
||
31 | { |
||
32 | byte finBitSetAsByte = isLastFrame ? (byte) 0x80 : (byte) 0x00; |
||
33 | byte byte1 = (byte) (finBitSetAsByte | (byte) opCode); |
||
34 | memoryStream.WriteByte(byte1); |
||
35 | |||
36 | // NB, dont set the mask flag. No need to mask data from server to client |
||
37 | // depending on the size of the length we want to write it as a byte, ushort or ulong |
||
38 | if (payload.Length < 126) |
||
39 | { |
||
40 | byte byte2 = (byte) payload.Length; |
||
41 | memoryStream.WriteByte(byte2); |
||
42 | } |
||
43 | else if (payload.Length <= ushort.MaxValue) |
||
44 | { |
||
45 | byte byte2 = 126; |
||
46 | memoryStream.WriteByte(byte2); |
||
47 | BinaryReaderWriter.WriteUShort((ushort) payload.Length, memoryStream, false); |
||
48 | } |
||
49 | else |
||
50 | { |
||
51 | byte byte2 = 127; |
||
52 | memoryStream.WriteByte(byte2); |
||
53 | BinaryReaderWriter.WriteULong((ulong) payload.Length, memoryStream, false); |
||
54 | } |
||
55 | |||
56 | memoryStream.Write(payload, 0, payload.Length); |
||
57 | byte[] buffer = memoryStream.ToArray(); |
||
58 | _stream.Write(buffer, 0, buffer.Length); |
||
59 | } |
||
60 | } |
||
61 | |||
62 | public void Write(WebSocketOpCode opCode, byte[] payload) |
||
63 | { |
||
64 | Write(opCode, payload, true); |
||
65 | } |
||
66 | |||
67 | public void WriteText(string text) |
||
68 | { |
||
69 | byte[] responseBytes = Encoding.UTF8.GetBytes(text); |
||
70 | Write(WebSocketOpCode.TextFrame, responseBytes); |
||
71 | } |
||
72 | } |
||
73 | } |