Getting the Internet Time, Page 3
You can simulate use of Telnet in Visual Basic by using the Winsock control.
All you need to do is perform a Winsock1.Connect, wait for the data to arrive, then Winsock1.Close. Simple as that. Let's knock together a sample project:
- Launch Visual Basic
- Create a new Standard EXE
- Click 'Project', 'Components'
- Check 'Microsoft Winsock Control 6.0', then click OK
- Draw out the new Winsock control onto Form1
The Winsock control is sort of like a programmable Telnet. It lets you connect to other computers and see how they respond.
- Add a Command Button to Form1
- Insert the following code behind the button:
Winsock1.RemoteHost = "pogostick.net"Winsock1.RemotePort = 13Winsock1.Connect
This code sets the properties of the Winsock control as we did in Telnet then attempts to connect. After we've connected, you might remember that the computer at the other end instantly sends back the current date and time, then terminates the connection. Let's code for that now:
- In the 'Object' drop-down list, select Winsock1
- In the adjacent 'Procedure' drop-down, select the 'DataArrival' event
The DataArrival event fires up whenever information is sent to your machine from the computer you're connected to. Let's add code to handle this now:
- Insert the following code behind the DataArrival event of your Winsock1 control:
Dim strData As StringWinsock1.GetData strData, vbStringMsgBox strDataWinsock1.Close
This is nothing special. First off, the information sent back from the server is stored in the strData variable then displayed in a message box. Finally, the computer connection is closed with the Winsock Close method. Let's test it all so far:
- Hit F5 to run your application
- Press your Command Button
You should be presented with a message box displaying something like, "Tue Sep 05 19:08:54".
If this isn't the exact time in your part of the world, you need to increase or decrease an hour or two depending on your time zone. You can handle this later.
Our most obvious problem is the stuff returned by this mega computer is just a piece of text. It's not a real "date", it can't fit into a variable of the Date data type.
Or can it?