Created
March 1, 2017 19:50
-
-
Save captainGeech42/81861246235315af0ff3a446d0f75f83 to your computer and use it in GitHub Desktop.
Snippet highlighting the socket server
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
public void RunTcpServer() | |
{ | |
while (_running) | |
{ | |
_listener.Start(); | |
DoBeginAcceptTcpClient(_listener); | |
_writer = new StreamWriter(_client.GetStream()); | |
_reader = new StreamReader(_client.GetStream()); | |
try | |
{ | |
//Client has requested an action | |
string requestRaw = _reader.ReadLine(); | |
string[] delim = { @"\|/" }; | |
string[] request = requestRaw.Split(delim, StringSplitOptions.None); | |
//Check if API key is valid | |
if (Config.GetApiKeys().Contains(request[0])) | |
{ | |
//Valid API key sent | |
Commands.Command command = (Commands.Command)Enum.Parse(typeof(Commands.Command), request[1]); | |
List<string> output = Commands.RunCommand(command); | |
foreach (string line in output) | |
{ | |
_writer.WriteLine(line); | |
} | |
//Send data back to client | |
_writer.Flush(); | |
} | |
else | |
{ | |
//API key was not found in the list | |
_writer.WriteLine("API Key Not Valid"); | |
//Send data back to client | |
_writer.Flush(); | |
} | |
} | |
catch (Exception e) | |
{ | |
_logger.LogError("Invalid command received"); | |
_writer.Write("Invalid command received"); | |
_writer.Flush(); | |
_client.Close(); | |
break; | |
} | |
_writer.Flush(); | |
_client.Close(); | |
_listener.Stop(); | |
} | |
} | |
private void DoBeginAcceptTcpClient(TcpListener listener) | |
{ | |
_clientConnected.Reset(); | |
listener.BeginAcceptTcpClient(DoAcceptTcpClientCallback, listener); | |
_clientConnected.WaitOne(); | |
} | |
private void DoAcceptTcpClientCallback(IAsyncResult ar) | |
{ | |
try | |
{ | |
_listener = (TcpListener)ar.AsyncState; | |
_client = _listener.EndAcceptTcpClient(ar); | |
_clientConnected.Set(); | |
} | |
catch (ObjectDisposedException e) | |
{ | |
//intentionally empty catch | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment