Created
June 19, 2020 08:26
-
-
Save msciborski/b2b8e18b19cf253cf4c2193fe4db9f90 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace Hl7v2MLLP | |
{ | |
public class TcpServer : IDisposable | |
{ | |
private readonly TcpListener _tcpListener; | |
public TcpServer(string ipAddress = "127.0.0.1", int port = 4321) | |
{ | |
try | |
{ | |
_tcpListener = new TcpListener(IPAddress.Parse(ipAddress), port); | |
_tcpListener.Start(); | |
Console.WriteLine("TcpListener started"); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e); | |
throw; | |
} | |
} | |
public async Task Listen() | |
{ | |
try | |
{ | |
while (true) | |
{ | |
var incomingTcpClientConnection = await _tcpListener.AcceptTcpClientAsync(); | |
Console.WriteLine($"Accepting incoming connection"); | |
var clientProcessingThread = new Thread(ProcessClientConnection); | |
clientProcessingThread.Start(incomingTcpClientConnection); | |
} | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e); | |
throw; | |
} | |
} | |
private void ProcessClientConnection(object args) | |
{ | |
var tcpClient = (TcpClient) args; | |
var buffer = new byte[200]; | |
var netStream = tcpClient.GetStream(); | |
var readData = String.Empty; | |
try | |
{ | |
int bytesReceived; | |
while ((bytesReceived = netStream.Read(buffer, 0, buffer.Length)) > 0) | |
{ | |
Console.WriteLine($"Bytes received: {bytesReceived}"); | |
readData += Encoding.UTF8.GetString(buffer, 0, bytesReceived); | |
} | |
System.Diagnostics.Debugger.Launch(); | |
Console.WriteLine($"Data: {readData}"); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e); | |
throw; | |
} | |
finally | |
{ | |
netStream.Close(); | |
netStream.Dispose(); | |
tcpClient.Close(); | |
} | |
} | |
public void Dispose() | |
{ | |
_tcpListener.Stop(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment