-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServerAsyncOldSyntax.cs
81 lines (72 loc) · 2.17 KB
/
ServerAsyncOldSyntax.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
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class ServerAsyncOldSyntax
{
TcpListener server = null;
public ServerAsyncOldSyntax(string ip, int port)
{
IPAddress localAddr = IPAddress.Parse(ip);
server = new TcpListener(localAddr, port);
}
public void Start()
{
Console.WriteLine("Starting Server...");
server.Start();
AsyncAcceptLoop();
}
private void AsyncAcceptLoop()
{
try
{
Console.WriteLine("Waiting for a connection...");
IAsyncResult result = server.BeginAcceptTcpClient(AcceptTcpClientCallback, null);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
server.Stop();
}
}
private void AcceptTcpClientCallback(IAsyncResult result)
{
TcpClient client = server.EndAcceptTcpClient(result);
Console.WriteLine("Connected!");
AsyncAcceptLoop();
HandleConnection(client);
}
public void HandleConnection(TcpClient client)
{
var stream = client.GetStream();
string data = null;
Byte[] bytes = new Byte[1024];
int byteCount;
try
{
while ((byteCount = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.ASCII.GetString(bytes, 0, byteCount);
Console.WriteLine($"Thread({Thread.CurrentThread.ManagedThreadId}) received: {data}");
string str = $"Welcome!";
Byte[] reply = System.Text.Encoding.ASCII.GetBytes(str);
stream.Write(reply, 0, reply.Length);
Console.WriteLine($"Thread({Thread.CurrentThread.ManagedThreadId}) sent: {str}");
}
}
catch(Exception e)
{
Console.WriteLine("Exception: {0}", e);
client.Close();
}
}
public static void Run()
{
Task.Run(() => {
var myServer = new ServerAsyncOldSyntax("127.0.0.1", 8080);
myServer.Start();
});
}
}