Lab 4
Lab 4
Lab 4
In this experiment, we will create a web server in C# using port 80. Google Chrome shall connect to this
port which will receive messages from the server.
First, we design our web page to host. You can save the file using notepad as “main.html” and open the
file to see how the page appears (optional). A sample HTML code is:
<html>
<head>
<title>My Web Server</title>
</head>
<body>
<h1>Welcome to My Web Server.</h1>
<br><br>'Drink Deep to Think Deep', Gandhi (whatever)
</body>
</html>
Now we store that HTML code in form of a string in our server code.
using System;
using System.IO;
using System.Net.Sockets;
using System.Net;
string tmp="";
string webs = "<html><body><title>My Web Server</title></body><h1>Welcome to My Web
Server.</h1><br><br>'Drink Deep to Think Deep', Gandhi whatever</html>";
for (;;) {
Socket socketForClient = tcpListener.AcceptSocket( );
if (socketForClient.Connected) {
Console.WriteLine("Connecting ...");
NetworkStream networkStream = new NetworkStream(socketForClient);
StreamWriter streamWriter = new StreamWriter(networkStream);
StreamReader streamReader = new StreamReader(networkStream);
tmp = streamReader.ReadLine();
Console.WriteLine("Connected. Recvd: {0}", tmp);
streamWriter.WriteLine(webs);
streamWriter.Flush();
}}}}
Tasks