Last active
July 2, 2016 18:14
-
-
Save NVentimiglia/d122e4cf801419b3b703041a1b56595c to your computer and use it in GitHub Desktop.
This file contains hidden or 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.Net; | |
using System.Net.Sockets; | |
using System.Threading.Tasks; | |
namespace TCPServer | |
{ | |
public class Program | |
{ | |
private static bool running = true; | |
public static void Main(string[] args) | |
{ | |
Run().Wait(); | |
} | |
public static async Task Run() | |
{ | |
TcpListener server = null; | |
try | |
{ | |
// Set the TcpListener on port 13000. | |
Int32 port = 13000; | |
IPAddress localAddr = IPAddress.Any; | |
// TcpListener server = new TcpListener(port); | |
server = new TcpListener(localAddr, port); | |
// Start listening for client requests. | |
server.Start(500000); | |
Console.Write("Waiting for a connection... "); | |
while (running) | |
{ | |
// Perform a blocking call to accept requests. | |
// You could also user server.AcceptSocket() here. | |
TcpClient client = await server.AcceptTcpClientAsync(); | |
// Enter the listening loop. | |
Task.Factory.StartNew(ReadAsync, client); | |
} | |
} | |
catch (SocketException e) | |
{ | |
Console.WriteLine("SocketException: {0}", e); | |
} | |
finally | |
{ | |
running = false; | |
// Stop listening for new clients. | |
server.Stop(); | |
} | |
} | |
private static async void ReadAsync(object state) | |
{ | |
TcpClient client = state as TcpClient; | |
while (running) | |
{ | |
Byte[] bytes = new Byte[1024]; | |
try | |
{ | |
client.NoDelay = true; | |
// Get a stream object for reading and writing | |
NetworkStream stream = client.GetStream(); | |
int i; | |
// Loop to receive all the data sent by the client. | |
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) | |
{ | |
// Send back a response. | |
stream.Write(bytes, 0, bytes.Length); | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
} | |
// Shutdown and end connection | |
client.Dispose(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment