Lab 4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

Lab 7 Getting your Web Server running in 5 Minutes

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.

Step 1: Creating a web page in HTML

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>

Step 2: Creating a web server

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;

public class NetworkIOServer {


public static void Main() {

Console.WriteLine("Web Server Started");


TcpListener tcpListener = new TcpListener(80);
tcpListener.Start( );

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

1. Modify the code to support multiple users at the same time.


2. Change the port 80 to something else. Can you now access that page now? Now use : operator in
chrome.
3. Modify the web page to also print date/time on the last line.
4. How can we add support for hyperlinks? What about complex webpages?