forked from nickproud/Easy-TCP-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Channel.cs
92 lines (82 loc) · 2.54 KB
/
Channel.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
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
namespace EasyTCP
{
public class Channel : IDisposable
{
private Server thisServer;
public readonly string Id;
private TcpClient thisClient;
private readonly byte[] buffer;
private NetworkStream stream;
private bool isOpen;
private bool disposed;
public Channel(Server myServer)
{
thisServer = myServer;
buffer = new byte[256];
Id = Guid.NewGuid().ToString();
}
public void Open(TcpClient client)
{
thisClient = client;
isOpen = true;
if(!thisServer.ConnectedChannels.OpenChannels.TryAdd(Id, this))
{
isOpen = false;
throw (new ChannelRegistrationException("Unable to add channel to channel list"));
}
string data = "";
using (stream = thisClient.GetStream())
{
int position;
while(isOpen)
{
while ((position = stream.Read(buffer, 0, buffer.Length)) != 0 && isOpen)
{
data = Encoding.UTF8.GetString(buffer, 0, position);
var args = new DataReceivedArgs()
{
Message = data,
ConnectionId = Id,
ThisChannel = this
};
thisServer.OnDataIn(args);
if(!isOpen) { break; }
}
}
}
}
public void Send(string message)
{
var data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);
}
public void Close()
{
Dispose(false);
isOpen = false;
thisServer.ConnectedChannels.OpenChannels.TryRemove(Id, out Channel removedChannel);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
}
stream.Close();
thisClient.Close();
disposed = true;
}
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}