/
SimpleServer.cs
101 lines (75 loc) · 2.34 KB
/
SimpleServer.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StudentsServerWeb
{
class SimpleServer
{
private IPAddress _ipAddress;
private AbstractResponder _helper;
private volatile bool _continue = true;
private TcpListener listener;
private NetworkStream stream;
private TcpClient client;
public SimpleServer() { }
public SimpleServer(string ipAddress, AbstractResponder helper)
{
try
{
_ipAddress = IPAddress.Parse(ipAddress);
}
catch (Exception)
{
throw;
}
this._helper = helper;
}
public void startListening(int port) {
try
{
while (_continue)
{
Thread.Sleep(10);
listener = new TcpListener(_ipAddress, port);
listener.Start();
Console.WriteLine("Listening on port " + port);
Console.WriteLine("The local End point is: " + listener.LocalEndpoint);
client = listener.AcceptTcpClient();
Console.WriteLine("Connection accepted from " + client.ToString());
byte[] bytes = new byte[8];
stream = client.GetStream();
stream.Read(bytes, 0, bytes.Length);
_helper.Respond(client, stream, bytes);
StopListening();
}
Console.WriteLine("server stopped");
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.ToString());
}
}
public void RequestStop()
{
_continue = false;
StopListening();
}
private void StopListening()
{
if (stream!=null)
{
stream.Close();
}
if (client != null)
{
client.Close();
}
listener.Stop();
}
}
}