-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
71 lines (64 loc) · 2.07 KB
/
Program.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace Server
{
public class HTTPServer
{
public static string StringToString(List<string> list)
{
string FinalString = "";
for (int i = 0; i < list.Count ;i++)
{
FinalString += list[i] + "\n";
}
return FinalString;
}
public static void DoIt(Socket acceptedSocket, List<string> messages)
{
Socket connectionSocket = acceptedSocket;
Console.WriteLine("Server activated");
Stream ns = new NetworkStream(connectionSocket);
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
sw.AutoFlush = true; // enable automatic flushing
messages.Add(sr.ReadLine());
while (!String.IsNullOrEmpty(messages[messages.Count - 1]))
{
Console.WriteLine("Client: " + messages[messages.Count - 1]);
try
{
sw.WriteLine(StringToString(messages));
messages.Add(sr.ReadLine());
}
catch (IOException ex)
{
Console.WriteLine("Exception !");
break;
}
}
ns.Close();
connectionSocket.Close();
}
public static void Main(string[] args)
{
List<string> messages = new List<string>(0);
messages.Add("Chat server messages: ");
TcpListener serverSocket = new TcpListener(6789);
serverSocket.Start();
Socket acceptedSocket;
int i = 0;
while ((acceptedSocket = serverSocket.AcceptSocket()) != null)
{
(new Thread(() => DoIt(acceptedSocket,messages))).Start();
i++;
}
serverSocket.Stop();
}
}
}