first commit
This commit is contained in:
94
TestDataServer/TestDataServer.cs
Normal file
94
TestDataServer/TestDataServer.cs
Normal file
@@ -0,0 +1,94 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
|
||||
namespace TestDataServer
|
||||
{
|
||||
class TestDataServer
|
||||
{
|
||||
private Mutex Mutex { get; set; }
|
||||
private Thread Thread { get; set; }
|
||||
private bool ShouldRun { get; set; }
|
||||
|
||||
public TestDataServer()
|
||||
{
|
||||
Mutex = new Mutex();
|
||||
ShouldRun = false;
|
||||
}
|
||||
|
||||
public void StartListening()
|
||||
{
|
||||
if (Thread == null)
|
||||
{
|
||||
ShouldRun = true;
|
||||
Thread = new Thread(new ThreadStart(this.ListenFunction));
|
||||
Thread.Start();
|
||||
}
|
||||
}
|
||||
|
||||
public void StopListening()
|
||||
{
|
||||
ShouldRun = false;
|
||||
}
|
||||
|
||||
void ListenFunction()
|
||||
{
|
||||
Socket listenSocket = new Socket(AddressFamily.InterNetwork,
|
||||
SocketType.Stream,
|
||||
ProtocolType.Tcp);
|
||||
|
||||
int port = 2664;
|
||||
|
||||
// bind the listening socket to the port
|
||||
IPAddress hostIP = (Dns.GetHostEntry(IPAddress.Any.ToString())).AddressList[0];
|
||||
IPEndPoint ep = new IPEndPoint(hostIP, port);
|
||||
listenSocket.Bind(ep);
|
||||
|
||||
// start listening
|
||||
listenSocket.Listen(64);
|
||||
|
||||
|
||||
while (ShouldRun)
|
||||
{
|
||||
Socket clientSocket = listenSocket.Accept();
|
||||
ThreadPool.QueueUserWorkItem(ClientProcessingFunction, clientSocket);
|
||||
}
|
||||
}
|
||||
|
||||
void ClientProcessingFunction(object context)
|
||||
{
|
||||
Socket clientSocket = context as Socket;
|
||||
|
||||
byte[] socketBuffer = new byte[1024];
|
||||
string data = null;
|
||||
|
||||
// Read data from client until EOF
|
||||
while (true)
|
||||
{
|
||||
int numByte = clientSocket.Receive(socketBuffer);
|
||||
|
||||
data += Encoding.ASCII.GetString(socketBuffer,
|
||||
0, numByte);
|
||||
|
||||
if (data.IndexOf("<EOF>") > -1)
|
||||
break;
|
||||
}
|
||||
|
||||
Console.WriteLine("{0}: Text received -> {1} ", Thread.ManagedThreadId, data);
|
||||
byte[] message = Encoding.ASCII.GetBytes("Test Server");
|
||||
|
||||
clientSocket.Close();
|
||||
}
|
||||
|
||||
public void WaitUntilThreadsClose()
|
||||
{
|
||||
while (Thread.IsAlive)
|
||||
{
|
||||
Thread.Sleep(33);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user