Skip to content

Instantly share code, notes, and snippets.

@lukasz-pyrzyk
Last active March 13, 2016 20:25
Show Gist options
  • Save lukasz-pyrzyk/c78484eea34212f8b492 to your computer and use it in GitHub Desktop.
Save lukasz-pyrzyk/c78484eea34212f8b492 to your computer and use it in GitHub Desktop.
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
int bufferSize = 1024 * 2;
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Socket client = listener.Accept();
byte[] packageSizeBuffer = new byte[sizeof(int)]; // buffer for integer
int position = socket.Receive(packageSizeBuffer); // read request size
int requestSize = BitConverter.ToInt32(packageSizeBuffer, 0);
byte[] request;
using (MemoryStream ms = new MemoryStream())
{
ms.Write(packageSizeBuffer, 0, position);
position = 0;
while (position != requestSize)
{
byte[] package = new byte[bufferSize];
int received = socket.Receive(package);
ms.Write(package, 0, received);
position += received;
}
request = ms.ToArray();
}
ProcessClientRequest(request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment