[C#]Process incoming GET/POST request
I have a simple C# web server that listens on certain port and can send back message with headers.
What I need to do is somehow receive incoming get/post data.
Any ideas how?
Code:
class Listener
{
private string _listenIp = "127.0.0.1";
private int _listenPort = 81;
private bool _isListening = false;
byte[] buffer = new byte[4096];
private Socket _serverSocket;
public string ListenIP
{
get
{
return _listenIp;
}
set
{
if (!_isListening)
{
_listenIp = value;
}
}
}
public int ListenPort
{
get
{
return _listenPort;
}
set
{
if (!_isListening)
{
_listenPort = value;
}
}
}
public bool IsListening
{
get
{
return _isListening;
}
set
{
}
}
public Listener(string ip, int port)
{
try
{
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_serverSocket.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
}
catch (Exception ex)
{
}
}
public void Start()
{
try
{
if (!_isListening)
{
_serverSocket.Listen(10);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
else
{
throw new Exception("Server is already listening on IP " + _listenIp + ":" + _listenPort);
}
}
catch (Exception ex)
{
}
}
private void AcceptCallback(IAsyncResult iar)
{
Socket clientSocket = _serverSocket.EndAccept(iar);
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private void ReceiveCallback(IAsyncResult iar)
{
try
{
Socket clientSock = (Socket)iar.AsyncState;
int bytesReceived = clientSock.EndReceive(iar);
if (bytesReceived > 0)
{
Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytesReceived));
Message myMsg = new Message(Encoding.ASCII.GetBytes("Sup dawg it's: " + DateTime.Now.ToString()));
myMsg.Send(clientSock);
clientSock.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Code:
class Message
{
private byte[] message;
public Message(byte[] msg)
{
message = msg;
}
public void Send(Socket client)
{
SendHeader(message.Length, "202 OK", ref client);
client.Send(message);
}
private void SendHeader(int lenght, string sStatusCode, ref Socket mySocket)
{
String sBuffer = "";
sBuffer += "HTTP/1.1" + sStatusCode + "\r\n";
sBuffer += "Server: cx1193719-b\r\n";
sBuffer += "Content-Type: " + "text/html" + "\r\n";
sBuffer += "Accept-Ranges: bytes\r\n";
sBuffer += "Content-Length: " + lenght + "\r\n\r\n";
Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer);
mySocket.Send(bSendData, bSendData.Length, 0);
}
}
Code:
class Program
{
static void Main(string[] args)
{
Listener myServer = new Listener("127.0.0.1", 8182);
myServer.Start();
Console.ReadLine();
}
}
ADDED:
I was staring at the code for half an hour trying to figure out what was wrong until I actually posted the code on ragezone and figured it all out lol. The power of ragezone :scared:
Anyway mods please add spoilers plz if possible and if anyone needs the code, feel free to use.