// Constructor
public MainPage()
{
InitializeComponent();
// create the socket
Socket listenSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
// bind the listening socket to the port
IPAddress hostIP = IPAddress.Parse("127.0.0.1");
IPEndPoint ep = new IPEndPoint(hostIP, 80);
listenSocket.Bind(ep);
// start listening
listenSocket.Listen(100);
SocketAsyncEventArgs saeAccept = new SocketAsyncEventArgs();
saeAccept.Completed += saeAcceptAsyncCompleted_Completed;
listenSocket.AcceptAsync(saeAccept);
// this.WebBrowser.Navigate(new Uri("http://127.0.0.1", UriKind.RelativeOrAbsolute));
}
int bufferOffsetReceive = 0;
void saeAcceptAsyncCompleted_Completed(object sender, SocketAsyncEventArgs e)
{
SocketAsyncEventArgs saeReceive = new SocketAsyncEventArgs();
byte[] buff = new byte[1024];
saeReceive.SetBuffer(buff, this.bufferOffsetReceive, buff.Length);
saeReceive.Completed += saeReceiveAsync_Completed;
saeReceive.UserToken = e.AcceptSocket;
e.AcceptSocket.ReceiveAsync(saeReceive);
}
void saeReceiveAsync_Completed(object sender, SocketAsyncEventArgs e)
{
var response = string.Format("<HTML><BODY><h1>HELLO from Windows Phone! :)) </h1> <br>This is a dynamic generated page from the device !<br>{0}</BODY></HTML>", DateTime.Now);
int Code = 200;
var scode = "OK";
string resp_header = "HTTP/1.1 " + (int)Code + " " + scode + "\n";
string[] Headers = new string[] { "Server: Windows Phone :)" };
foreach (string header in Headers)
{
resp_header += header + "\n";
}
byte[] Body = Encoding.UTF8.GetBytes(response);
resp_header += "Content-Length: " + Body.Length + "\n\n";
MemoryStream ms = new MemoryStream();
var buff = Encoding.UTF8.GetBytes(resp_header);
ms.Write(buff, 0, buff.Length);
ms.Write(Body, 0, Body.Length);
ms.Flush();
var responseBuffer = ms.GetBuffer();
SocketAsyncEventArgs saeSend = new SocketAsyncEventArgs();
saeSend.SetBuffer(responseBuffer, 0, responseBuffer.Length);
var socket = e.UserToken as Socket;
socket.SendAsync(saeSend);
//ThreadPool.QueueUserWorkItem(new WaitCallback(_ConnectionThreadEntry), tcpConnection);
}