Wednesday, January 11, 2012

A Very Basic Web Server Test

Writing network related programs is fun and exciting. At times it almost seems like magic. This source code sample shows how you can create a very basic web server that when your browser connects to it the specified text will show up in the browser. This uses the Microsoft Winsock control.

This source code sample demonstrates how you can create a very, very, basic web server. It is not intended for you to actually use but instead to just wet your appetite with a simple networking example. Before someone leaves a nasty comment read this: I am in no way calling this a true web server - just a simple fun example.

What you will end up with after using this very simple code snippet is a little server running in VB that when a web browser hits it will return out whatever text you have set up. I know when I first started playing with networking development it seemed kind of like magic. You can very quickly begin to understand how web servers, a virtual private server, chat programs, email programs, etc. work.

To use this code example do the following: Create a new VB program. Next place a command button on your form named command1 and set the caption to Start Server, you will also need to place the Winsock control on the form. Set its name to Winser. If you don't know how to put a winsock control on your form check out this Client server tutorial to see how. Lastly place the code below into the source code area for your form.

Private Sub Command1_Click()
WinSer.LocalPort = 80
WinSer.Listen
Command1.Enabled = False
End Sub

Private Sub WinSer_ConnectionRequest(ByVal requestID As Long)
WinSer.Close
WinSer.Accept requestID
End Sub

Private Sub WinSer_DataArrival(ByVal bytesTotal As Long)
Dim DataSend As String
DataSend = "Webserver Test"
DataSend = DataSend & vbNewLine & Now
WinSer.SendData DataSend
End Sub

Private Sub WinSer_SendComplete()
WinSer.Close
End Sub

Once you have the code in place press F5 to run your program. Then pull open a web browser and navigate to http://localhost - This will connect to your VB web server and you should see "Webserver Test" show up in your browser.

Obviously this just barely scratches the surface as to what we can do with the winsock control. You can write virtually any networking application you can think of. If you would like to go more in depth with writing client server or other networking programs check out the links below.

Note: The source for this was found at DreamVB which is no longer online.

0 comments:

Post a Comment