Including Web functionality in an application in the past involved Winsock programming. Winsock programming has been perceived as a barrier by many programmers. Development involving TCP/IP networking appeared to be an arcane craft known only to initiates of the black arts. For Microsoft to reach its goal of making the Internet--and the use of Internet technology for intranets-- accessible to all, this barrier needed to be removed. To this end, Microsoft developed a superb suite of tools.
Three of the tools that Microsoft created for use in Visual Basic 5.0 are ActiveX controls that ease the road to Internet functionality. One of these ActiveX controls is the Microsoft Winsock Control Version 5.0. This control parks invisibly on a Visual Basic form, which acts as a client, and provides TCP/IP communication with a server program that also has a Winsock control. Another of the three controls is the Microsoft Internet Transfer Control Version 5.0. This control is used to transfer files between clients and servers on a TCP/IP network by using protocols such as HTTP and FTP. The third of the ActiveX controls is the WebBrowser Control, which is used to display HTML pages. The Winsock API is wrapped in these controls and exposed through their properties, methods, and events. If you can write a Visual Basic "Hello World" application, you can create powerful client/server applications that will communicate over a TCP/IP network link.
Use of the Winsock Control is not limited to the Web browser paradigm or to the use of the HTTP or FTP protocols. It lives at a lower level, using the TCP and UDP protocols. The other Microsoft controls encapsulate the specifics of the HTTP and FTP protocols.
In this chapter, you will explore TCP/IP fundamentals; examine in some detail the Microsoft Winsock Control, Internet Transfer Control, and the WebBrowser Control; and build a working client/server application.
Winsock is a short name for Windows Sockets. Sockets provide a standard programming interface for communications programming with the TCP/IP protocol. The Win32 API includes the Winsock API, which is a fairly straight port of the Berkeley Sockets API for Windows. It encompasses the event-driven nature of Windows programming. Microsoft has added extensions to the Winsock API, which constitute the INetAPI. These extensions are aimed at extending the functionality of HTTP, FTP, and Gopher.
NOTE: There are several excellent books on TCP/IP and Microsoft TCP/IP, which is Microsoft's implementation of TCP/IP. In the Microsoft world of TCP/IP, you might also want to explore DHCP (Dynamic Host Configuration Protocol) and WINS (Windows Internet Name Service). The information in this chapter will enable you to use the Winsock Control with little or no trouble.
See Sams' TCP/IP Unleashed, Second Edition, for in-depth coverage of TCP/IP.
Networked applications often use the paradigm of client/server. The client contacts the server and requests information or service from the server application. The server responds by providing the data or service.
In the world of Winsock communications, the important aspect of the client/server relationship is who establishes the connection. Chapter 41, "Using Visual Basic in a Client/Server Environment," covers the client/server world in more depth. The client is always the initiating application. The client sends a request for connection to the server. After the connection has been established, the server can request information from the client and vice versa. Once the connection has been established, a peer relationship exists, with either application being able to initiate communication.
When a system is part of a TCP/IP network, it needs to have an identification address. This address, called the IP or Internet Protocol address, is a 32-bit number that is usually represented by four numbers separated by periods. An example is 190.137.48.1. This is the decimal representation of four bytes. When assigned to your computer, this number is its node address, whether your system is attached to the Internet, to your company LAN, or to a system of two computers at home that you have attached in a small local LAN.
Because numbers can be hard to remember, a system of "friendly" names has been created wherein each computer has a name--the domain name. An example is the Microsoft domain name of www.microsoft.com. In the friendly name system, this represents a node on the network.
NOTE: The domain name www.microsoft.com is actually composed of multiple computers that are all reached by the domain name of www.microsoft.com. A system called round robining is used to have multiple computers available to respond when one friendly domain name is used. As Microsoft is one of the busiest Web sites in the world, it is understandable that one system can't handle the load.
Friendly names are difficult for computers to work with as addresses, so a system called the Domain Name Service (DNS) was devised. Domain Name Service translates the friendly names into IP addresses. This is accomplished by computers on the network that are Domain Name Servers. When you enter a request for service on the World Wide Web, the address is specified as an URL, or Universal Resource Locator. http://www.microsoft.com is an example. http is the protocol used and www.microsoft.com is the name of a system somewhere on the Internet. The essence of the process is that the www.microsoft.com address is translated by a DNS into an IP address, such as 190.137.12.4. Now the network can work with the address and locate the system to which you want to attach.
The key factor to remember is that a system on a network can be referred to by either the IP address or the friendly name. If there is a system on the network providing Domain Name Services, the name will be resolved into an IP address. The IP address is the "real" address. The friendly name is an "alias" that is easier to remember.
When data is moved across the network with the TCP/IP protocol, there are two methods used: User Datagram Protocol (UDP) and Transmission Control Protocol (TCP). UDP and TCP are quite different and each has its uses. One is not better than the other. Both are available to you when using the Winsock Control, for example. In the use of HTTP or FTP, the protocol decides which will be used. In general, if you are not sure which one to use, TCP will always work, but it imposes a higher overhead cost.
UDP UDP is somewhat like mailing a letter. When a message is sent over the network with UDP, the message is packaged up with a destination address (the IP address of the system to which it is being sent) and the address of the system sending the message (again, an IP address). The theoretical maximum size for a UDP message is 65K bytes. Many implementations are less than this size. A size of 8192 bytes is the usual smallest maximum size that all implementations will accommodate. If the Datagram exceeds the maximum permissible size for the implementation, the message is simply truncated. After the message is packaged with the destination and origin addresses, it is sent on a best-efforts basis, with no guarantee that it will arrive and no checking performed by the protocol to see if it did arrive. Any checking must be performed in the application. This is a connectionless communication. There is no checking to see if the destination system is capable of receiving a message.
The UDP message also contains the source port and the destination port numbers. Ports are discussed later in this chapter in the section "Ports."
An example of a service that uses UDP is the Simple Mail Transport Protocol (SMTP) for e-mail messages. This is very much like mailing a letter. There is no assurance that it will arrive. This is an unreliable communication protocol.
TCP With TCP, there is no maximum message length. When a message passed to the TCP protocol is too large to be sent in one piece, the message is broken up into chunks or packets and then sent one chunk or packet at a time to the destination address. The TCP packet contains the addressee information, as does the UDP message, with one addition: The TCP message also contains a packet number and the total number of packets. Because of the nature of the TCP/IP protocol, the packets might travel different paths and might arrive in a different order than when sent. TCP reassembles the packets in the proper order and requests the retransmission of any missing or corrupted packets. Unlike UDP, TCP is a connection-oriented, reliable communication protocol. Using it is somewhat like dialing a telephone and waiting for someone to answer before beginning to talk or send data.
With TCP, the client system sends a request for connection, as previously discussed. As with the UDP protocol, the TCP messages contain destination and origin port numbers.
The TCP/IP protocol is used for communication between computer systems. Port numbers are used for communicating between applications on the two systems. Ports are also called sockets. This is the origin of the Winsock terminology.
When two applications are communicating by using the TCP/IP protocol, the applications use port numbers to identify themselves to the other application. When a server receives a request for a connection, the request is directed to a particular TCP/IP port. The server then knows which application is being contacted because it has the port number associated with the application.
This is analogous to having two phones in your house, one for business and one for personal use. If the business phone rings, you know that when you answer, the caller will request the attention of your business persona, not your private persona.
Servers listen on a particular port, and clients send requests to that port. In the everyday world of Internet usage, there are Well Known Ports. Some of these ports have become standard. The World Wide Web uses Port 80, and FTP uses Port 21. WWW would function just as well on Port 37, but "everyone" has agreed that Port 80 will be used.
This is similar to the use of 911 for an emergency phone number. 919 would have worked just as well, but the use of 911 has been accepted almost nationwide.
A particular server application listens on a specific port number for requests to connect to that server. If you have a system that is used for both WWW and FTP, it will listen on both Ports 21 and 80. If the request for connection comes in on Port 80, the Web server application handles the communication.
Having a system work as a server for one application does not prevent it from being a client for another application. A system can be a Web server listening on Port 80 and communicate contemporaneously with another system on another Port for a different application.
An important point to remember is that the client system does not have to send the request for service from the same port on which the server is listening. For example, if the server ABC application is listening on Port 239, the client may send its request for service from its Port 1593 to the server's Port 239. This works because the client tells the server the port number that its request came from, so the server responds to the client by sending the response to Port 1593.
The essential parts of the message sent from one computer system to another are the following:
There are other components of the message, but they are not important for this discussion.
HTTP is one of the protocols that uses the basis of TCP/IP in a specific implementation. This is the protocol of the World Wide Web. You may hear reference to an HTTPD server, which refers to the Hypertext Transfer Protocol Daemon.
NOTE: Daemon is UNIX-speak for a program or process that runs continuously in the background. In Windows NT-speak, this is usually a service or server, such as a Web server or an FTP server that listens on a port for incoming requests for service. If a daemon is not running, no connection can be made. This is why failed e-mail is often returned by a daemon.
HTTP currently is in version 1.0 and moving toward version 1.1. Most Web servers will be updated in the near future to support 1.1, as will Web browsers. There will be backward compatibility for both servers and browsers.
HTTP is a very simple protocol. The client, usually called a browser, issues a request to the server. The server responds with the requested file and closes the connection.
There are two HTTP message types: requests and responses. There are three types of requests: GET, HEAD, and POST. In a GET request, a file is requested. In a HEAD request, only the server header information is returned. In a POST request, the BODY is transmitted to the server, and it contains data such as an HTTP form or a MAIL message.
HTTP Request The format of an HTTP request is the following:
request-line headers (0 or more) <blank line> body (only for POST requests)
The format of the request-line is:
request request-URL HTTP/Version
An example of a request-line is:
GET /afile.htm HTTP/1.0
HTTP Response The format of the HTTP response is:
status-line headers (0 or more) <blank line> body
The body usually will be an html file that contains formatting tags and links that are used in other requests. The format of the status-line is:
HTTP/version response-code response-phrase
An example of a status-line is:
HTTP/1.0 200 OK
There are a number of other status codes. If you have spent any time on the Web, you have seen the 404 Not Found response.
FTP is the TCP protocol that is widely used to transfer files. A brief description of the details of the FTP protocol will help you understand the details of an FTP session.
There are two types of connections established in an FTP session: a control connection and a data connection.
Control Connection The control connection, which is maintained throughout the FTP session, is used to transmit commands between the client and the server. The first step in the FTP session process consists of the server listening on FTP's well-known port, Port 21. The FTP server listens by performing a passive open of a control connection, which waits for an active open control connection request.
The second step in the FTP session process consists of the client sending an active open control connection request to the FTP server, which request is addressed to Port 21. If all of the logon requirements are met, an active control connection is created between the client and the server. This connection stays open throughout the FTP session. Commands and replies are communicated over this connection.
Data Connection A data connection is established each time a file is transferred and is maintained only so long as the file transfer is in process. The client establishes a data connection to either upload or download a file. When the file has been transferred, the data connection is terminated.
When the client is finished with the FTP session, a command terminating the control connection is sent to the server and the FTP session is terminated.
NOTE: Gopher essentially is a menu-driven front end to an anonymous FTP. It is quite similar to HTTP in its usage. However, Gopher is declining in usage and might fall into complete disuse in the near future. Gopher uses Port 70. It is considered a legacy protocol by many Web users. Most Web browsers support the Gopher protocol, and it is one of the protocols supported by the Microsoft Internet Transfer Control.
The Winsock Control operates at a very basic level of TCP/IP. It does not use the HTTP or FTP protocols. For example, it could be used if you wanted to create your own two-person chat room application to create and maintain the connection and manage the details of the data transfer.
As stated earlier, the Winsock API is wrapped in the Winsock Control. The API functions are accessed through the properties, methods, and events of the Winsock Control, which are discussed in detail in the following sections.
Properties have several attributes, such as:
Another aspect of a property is the data type of the value. This can be a string, an integer, a long integer, or any other data type.
The third important aspect of a property is the syntax or usage of the property in code.
BytesReceived Property The BytesReceived property tells you the number of bytes that are currently in the receive buffer. It is read-only and is unavailable at design time. The value returned is a long integer. An example of the syntax is:
myvar = MyWinsockControl.BytesReceived
You might use the BytesReceived property to determine the size of a display area for the data or to see if there is any data in the buffer.
LocalHostName Property The LocalHostName property returns the name of the local host system. LocalHostName is read-only and is unavailable at design time. The value returned is a string. An example of the syntax is:
myvar = MyWinsockControl.LocalHostName
LocalIP Property The LocalIP property returns the local host system IP address in the form of a string, such as XXX.XXX.XXX.XXX, where the X's represent the numbers in an IP address. This property is read-only and is unavailable at design time. The value returned is a string. An example of the syntax is:
myvar = MyWinsockControl.LocalIP
LocalPort Property The LocalPort property returns or sets the local port number. LocalPort is both read and write and is available both at design time and at run time. The value returned is a long integer. An example of the syntax to read the property is:
myvar = MyWinsockControl.LocalPort
To set the property, you use:
MyWinsockControl.LocalPort = 1001
An example of using this property is setting the port prior to using the Listen method to set the port number for the application. This allows selection of the port at run time.
Protocol Property The Protocol property returns or sets the protocol of either UDP or TCP. This property is both read and write and is available both at design time and at run time. (Note that at run time the control must be closed--see the upcoming State property.) The value returned is 0, or the constant sckTCPProtocol, or 1, or sckUDPProtocol. An example of the syntax to read the property is:
myvar = MyWinsockControl.Protocol
To set the property, you use:
MyWinsockControl.LocalPort = sckTCPProtocol
RemoteHost Property The RemoteHost property returns or sets the remote host. RemoteHost is both read and write and is available both at design time and at run time. The value returned is a string and can be specified either as an IP address (XXX.XXX.XXX.XXX) or as a friendly name, such as www.microsoft.com. An example of the syntax to read the property is:
myvar = MyWinsockControl.RemoteHost
To set the property, you use:
MyWinsockControl.RemoteHost = "192.143.29.47"
Setting this property at run time allows the remote host to be selected when the application starts or to be selected based upon some criteria.
RemotePort Property The RemotePort property returns or sets the remote port number. This property is both read and write and is available both at design time and at run time. The value returned is a long integer. An example of the syntax to read the property is:
myvar = MyWinsockControl.RemotePort
To set the property, you use:
MyWinsockControl.RemotePort = 1001
This property can be used to select the application that is to be contacted at the remote host.
State Property The State property returns the state of the control as expressed by an enumerated list. This property is read-only and is unavailable at design time. The State property is set by using various methods and events. The syntax to read the property is:
myvar = MyWinsockControl.State
The settings for the State property are set forth in Table 40.1.
Constant | Value | Description |
sckClosed | 0 | Default Closed |
sckOpen | 1 | Open |
sckListening | 2 | Listening |
sckConnectionPending | 3 | Connection pending |
sckResolvingHost | 4 | Resolving host |
sckHostResolved | 5 | Host resolved |
sckConnecting | 6 | Connecting |
sckConnected | 7 | Connected |
sckClosing | 8 | Peer is closing the connection |
sckError | 9 | Error |
The State property needs to be checked before state-changing methods are used. For example, attempting to open a closed Winsock Control will result in an error.
Methods are predefined functions that are used to perform various tasks on the control. There are methods that open and close a connection and methods that accept a request for the connection. Some of the important methods used with the Winsock Control are discussed in the following sections.
Accept Method The Accept method is used for the TCP server applications only. It accepts the request for connection from a client system. For the Accept method to be used, the control must be in a listening state. This method is used in conjunction with the ConnectionRequest event, which is discussed below. The syntax for the Accept method appears as follows:
Private Sub MyWinsockControl ConnectionREquest (ByVal requestID as Long) MyWinsockControl.Accept End Sub
Close Method The Close method is used to terminate a TCP connection from either the client or server applications. The syntax is:
MyWinsockControl.Close
GetData Method GetData is the method used to retrieve the current block of data from the buffer and then store it in a variable of the variant type. The syntax is:
MyWinsockControl.GetData myvar
Listen Method The Listen method is invoked on the server application to have the server application wait for a TCP request for connection from a client system. The syntax is:
MyWinsockControl.Listen
SendData Method The SendData method is used to dispatch data to the remote computer. It is used for both the client and server systems. The syntax is:
MyWinsockControl.SendData myvar
Events are the triggers that invoke the methods. An example of an event is a mouse click. The events from other objects, such as a command button, are used to trigger some of the methods in the preceding section. The Winsock Control generates events that also can be used. Some of these events, such as the ConnectionRequest event, happen at the server system as a result of an action taken at the client system. The events generated by the Winsock Control make it possible for an unattended system to participate in a network communications session.
Close Event The Close event occurs when the remote computer closes the connection. The event can be used to do cleanup work at the end of a session. The syntax is:
Private Sub MyWinsockControl_Close()
Connect Event The Connect event occurs after the connection with the remote computer has been made. The syntax is:
Private Sub MyWinsockControl_Connect()
ConnectionRequest Event The ConnectionRequest event occurs when the server receives a request for connection from a client system. The syntax is:
Private Sub MyWinsockControl_ConnectionRequest(requestID As Long)
DataArrival Event The DataArrival event occurs when new data arrives. The syntax is:
Private Sub MyWinsockControl_DataArrival (ByVal bytesTotal As Long)
The client always initiates the conversation, and the server must provide appropriate answers. At any point, if either party does not keep the exchange going, the connection is broken and the conversation ends. If the conversation ends without the proper cleanup, the conversation cannot be reinitiated until the applications have been reset.
The sample application that is contained in this chapter is a form of chat, in which both the client and server are capable of sending text to one another.
This is a very simple application. There is no error trapping, so the application is not robust. When an error occurs, both the client and the server must be closed and reopened. This way, you have all the fun of adding the error trapping. The complete code for this application is on the companion CD and is yours to use.
The project is contained in the Chapter 41 directory. Both the Visual Basic projects and a compiled version of the programs are there.
When the project is started, two controls must be added to the default Visual Basic Toolbox. These controls are the RichTextBox control and the Microsoft Winsock 5.0 Control. These are added by choosing Project, Components and then selecting the two components in the list presented.
When designing this sample client application, the designers determined that the user would want to see messages and replies in two separate text boxes. RichTextBoxes were selected because of their capability to use text formatting, and these text boxes were designated InBound and OutBound.
A command button was added to initiate the connection.
Two more text boxes were added to enter the remote host name or IP address and the remote port, which enables the host and port to be selected and set at run time.
A final text box was added to display the local port number. This local port number can be read before the connection is created and after the connection is made.
And last, but certainly not least, a Microsoft Winsock Control 5.0 is added. This Winsock Control manages the communications between the client and server systems.
Laying Out the Form The Visual Basic form for the client application at design time is shown in Figure 40.1. When the application runs, you need to enter the remote host name or IP address and the remote port number before clicking the Connect button. After the connection is established, you can enter text in the Outbound Text box. When entered, text is automatically dispatched to the Server application. When you enter a character in the Outbound text box, a change event is triggered, and its attached event handler sends the contents of the text box to the remote host.
FIG. 40.1
Notice that the Winsock Control is visible at design time.
In Figure 40.2, the appearance of the form at run time is the same as the design-time appearance, with the exception that the Winsock Control is not visible.
FIG. 40.2
The Remote Host and Remote Port setting must be entered before the connection
is attempted in this example program.
Adding the Code This section examines the code from the client application, just as it appears in the program. Take notice of the small amount of code that is required to create the functionality of the application. The addition of error handling would more than double the code. Here, you can see the power of the Winsock Control. In a very few lines of code, full TCP/IP communication is accomplished. In Listing 40.1, a command button is used to initiate the connection. The Connect method is used. This method gathers the current values in two properties, the RemoteHost property and the RemotePort property, and creates the TCP message that contacts the remote host and requests the connection. By setting two properties and calling one method, you have accomplished what could have required hours or even days of programming to accomplish if you were not using the Winsock API.
Option Explicit Private Sub cmdConnect_Click() `The command button click event is used to create the `connection. ` The connection request string is sent to the RemoteHost ` on the RemotePort. ` The Connect method takes two arguments, in the form of ` object.Connect remoteHost, remotePort ` If the two properties are blank and the arguments are ` ot supplied an error occurs. ` The two properties were set in the Form_Load ` event which occurs prior to the Command_Click event. wskClient.Connect End Sub
Listing 40.2 shows the sub that is provided to enable you to see that the local port is set to 0 before the connection is made, and will be set to a value selected by the system in the process of making the connection.
Private Sub cmdReadLocalPort_Click() `This will read and display the value of the LocalPort `property in txtLocalPort.Text txtLocalPort.Text = wskClient.LocalPort End Sub
Listing 40.3 shows the sub that enables the RemoteHost property to be set at run time. If the client is always going to communicate with the same server, the RemoteHost property can be set at design time.
Private Sub cmdSetRemoteHost_Click() `This will set the value of the RemoteHost property to the `value in txtRemoteHost.Text wskClient.RemoteHost = txtRemoteHost.Text End Sub
Listing 40.4 shows the sub that enables the RemotePort property to be set at run time. If the client is always going to communicate with the same port number, the RemotePort property can be set at design time.
Private Sub cmdSetRemotePort_Click() `This will set the value of the RemotePort property to ` the value in txtRemotePort.Text wskClient.RemotePort = txtRemotePort.Text End Sub
Listing 40.5 shows another method for setting the RemoteHost and RemotePort properties in code.
Private Sub Form_Load() `The name of the Winsock control for the client is wskClient ` This name is the object when setting a property such as ` object.property or wskClient.Property `The name of the remote host can be set at design time in the ` properties dialog or it can be set at runtime in code. ` Either the IP address "XXX.XXX.XXX.XXX" or a ` friendly host ` ame may be used such as "http://www.microsoft.com" ` The RemoteHost property has a data type of string. wskClient.RemoteHost = "SomeJunk" `The RemotePort property can be set at design time `or in code at run time. ` The RemotePort property has a data type of Long Integer. ` This is port number on which the Server will be ` listening. wskClient.RemotePort = 1002 End Sub
Using the Change event to send the entire contents of a RichTextBox, as shown in Listing 40.6, is an inefficient technique because the entire message is retransmitted with each change in the contents. However, it does illustrate the simplicity of sending data with the SendData method.
Private Sub rtbClntOutBound_Change() `The RichTextBox_Change event is being used to send data. `The contents of the ` RichTextBox rtbClntOutBound will be transmitted each ` time the contents of the ` Text property is changed. The SendData method is used ` with the argument of ` RichTextBox.Text wskClient.SendData rtbClntOutBound.Text End Sub
Listing 40.7 shows a two-step process of moving the data from the buffer into a variable and then placing the variable contents into the Text property of the RichTextBox control. It can be placed directly into the Text property of the RichTextBox control.
Private Sub wskClient_DataArrival(ByVal bytesTotal As Long) `The variable strData is declared to hold the incoming data. `It is stored as a variant. Dim strData As String `The GetData method takes the data from the incoming buffer `and places it in the strData variable. wskClient.GetData strData `The strData variable contents are placed in the `RichTextBox rtbClntInBound.Text property rtbClntInBound.Text = strData End Sub
The salient feature of the client application program code is its simplicity. The assertion made at the beginning of the chapter was not an exaggeration--if you can write a "Hello World" application, you can use the Winsock Control.
When the sample server application was designed, the primary requirement was that the application be capable of servicing the needs of the client application. The server application looks like a mirror image of the client application, with the exception that it cannot initiate a connection.
The users see their messages and the replies in two separate text boxes. RichTextBoxes were selected to correspond to the client application. The RichTextBoxes were, again, designated InBound and OutBound.
A text box is added to display the Remote Port number. This enables you to see that the Local Port on the Client Application and the Remote Port on the Server Application are the same.
Another text box is added to display the State property of the server. This changes from 2 (listening) to 7 (connected) as the application runs.
A final text box is added to display automatically the requestID that is sent by the client application or, optionally, to display the Local Port number for the server.
Of course, a Microsoft Winsock Control 5.0 is added to manage the communications between the client and server systems.
Laying Out the Form The Visual Basic form for the server application at run time is shown in Figure 40.3. When the application runs, the server application is in a listening state. It waits for a client system to initiate a connection.
FIG. 40.3
There is no command button to initiate the connection on the server application
form.
Adding the Code This section examines the code from the server application. Notice the small amount of code that is required to create the functionality of the application. The addition of error handling would, at the very least, double the total amount of code. Just as with the client application, very little code is required to utilize the power of the Winsock Control. In Listing 40.8, a command button Click event is used to display the local port number. Because this is set by the From Load event, it will read 1001, as set in the Sub Form_Load() section.
Option Explicit Private Sub cmdReadLocalPort_Click() `This reads and displays the LocalPort property. txtrequestID.Text = wskServer.LocalPort End Sub
The code in Listing 40.9 displays the remote port number. Display this number before and after the connection is made and you will see that the remote port number is set at the time the connection is made.
Private Sub cmdReadRemotePort_Click() `Read the RemotePort property and display `in the txtRemotePort. txtRemotePort.Text = wskServer.RemotePort End Sub
Server state is an enumerated list. A ServerState of 2 is currently listening, and a ServerState of 7 is connected. The code in Listing 40.10 displays the current server state.
Private Sub cmdReadServerState_Click() `Read and Display the current Server State txtServerState.Text = wskServer.State End Sub
In Listing 40.11, the Form_Load event is setting the local port number for the Server Winsock Control and is using the Listen method to place the server application in a listening state.
Private Sub Form_Load() `The name of the Winsock control for the server is wskServer ` This name is the object when setting a property such as ` object.property or wskServer.Property `The LocalPort property can be set at design time or in `code at runtime. ` The LocalPort property has a data type of Long Integer. ` This is port number on which the Server will be listening ` and must match the RemotePort property of the Client. wskServer.LocalPort = 1001 `The Listen method is used to start the server monitoring `incoming requests for a connection. wskServer.Listen End Sub
Listing 40.12 shows the RichTextBox_Change event being used to send data to the client application.
Private Sub rtbServOutBound_Change() `The RichTextBox_Change event is being used to send data. `The contents of the RichTextBox rtbServOutBound will be ` transmitted each time the contents of the ` Text property is changed. The SendData method is used ` with the argument of RichTextBox.Text wskServer.SendData rtbServOutBound.Text End Sub
Listing 40.13 shows the ConnectionRequest event being used to open the connection. The Accept method establishes the connection. The request ID is also displayed in a text box.
Private Sub wskServer_ConnectionRequest(ByVal requestID As Long) `Check to determine whether the WinSock Control's state is `closed. ` If it is not, then close the control before using the ` Accept method. If wskServer.State <> sckClosed Then wskServer.Close `The control is now prepared to use the Accept method ` which will receive the ` ConnectionRequest from the Client. ` The argument for the Accept method is requestID wskServer.Accept requestID `The requestID is displayed txtrequestID.Text = requestID End Sub
Listing 40.14 uses the DataArrival event to display the data in a RichTextBox.
Private Sub wskServer_DataArrival(ByVal bytesTotal As Long) `The variable strData is declared to hold the incoming data. ` It is stored as a variant. Dim strData As String `The GetData method takes the data from the incoming ` buffer and places it in the strData variable. wskServer.GetData strData `The strData variable contents are placed in the ` RichTextBox rtbClntInBound.Text property rtbServInBound.Text = strData End Sub
As with the code for the client application, the code required for the server Winsock Control is only a few lines. This is a truly powerful control.
The client/server application can be run on the same system or on two different systems that are on the same network. The application will run on a Windows NT 4.0 or Windows 95 system. The primary requirement is that TCP/IP be installed on the system and that the TCP/IP stack is running. This usually is not a problem on a Windows NT system. Occasionally, you may need to start the TCP/IP stack on a Windows 95 machine. One of the easiest ways to do this is to open a connection to your ISP (Internet Service Provider). This starts the TCP/IP stack on a Windows 95 machine and allows the Winsock Control to be used.
To run the application, use the Windows Explorer to go to the Chapter 41 directory on the CD and then double-click both WebDev05Client.exe and WebDev05Server.exe. This starts both programs, as shown in Figure 40.4.
When both programs are running, you need to set the remote host name in the client application. You accomplish this by entering the name of the system or the IP address of the system that is running the server application in the text box labeled Remote Host and then clicking the Set RemoteHost button. You also need to click the Set RemotePort button. Leave the default value of 1001. Now click the Connect button on the client application. A requestID number should appear in the requestID text box on the server system, as shown in Figure 40.5.
FIG. 40.4
These programs can be run on two systems that are connected on a local network
by using the TCP/IP protocol.
FIG. 40.5
The Read buttons at the bottom of the application windows can be used to show
various properties.
You are now ready to use the application for its designed purpose--a simple chat application. By typing inside the Outbound text boxes, you will see the information that you enter displayed in the Inbound box of the other application window, as shown in Figure 40.6.
FIG. 40.6
The information entered is displayed on a character-by-character basis.
The code and project for this demonstration program is also on this book's companion CD-ROM. As you experiment with the programs, you will find that the principles of the program are very simple. The Winsock Control is very easy to use.
The Microsoft Internet Transfer Control enables the implementation of two of the most significant and widely used Internet protocols: Hypertext Transfer Protocol (HTTP) and File Transfer Protocol (FTP) are the workhorses of the Internet. With HTTP, you can connect to World Wide Web servers and retrieve HTML and other documents. By using FTP, you can download and upload files between systems on the Internet or an intranet.
The Internet Transfer Control has properties, methods, and events, just as all ActiveX controls have. Understanding these properties, methods, and events is the key to understanding the control and what can be done with it.
Some properties are available to be set at design time, while others are read-only at run time and unavailable at design time. Still others can only be set at design time and are read-only at run time. Some properties, though, can be set at both run time and at design time.
The data type of the property is important to know and understand. A data type can be a string, an integer, a long integer, or any other data type.
You also must understand the syntax for using the property in code.
AccessType Property The AccessType property determines whether the control will directly access the network (Internet or intranet) or access the network through a proxy.
NOTE: Proxies can be used to link LANs to the Internet. In addition to providing access to the Internet, these proxies act as a firewalls, preventing unwanted intrusion into the LAN from the Internet.
The syntax for AccessType is:
MyInetControl.AccessType = type
Following is an enumerated list of integers and constants for the AccessType:
Integer | Value | Description |
icUseDefault | 0 | The control uses the default setting found in The Registry. |
icDirect | 1 | The connection is direct to the Internet. |
icNamedProxy | 2 | The control uses the proxy server named in the Proxy property. |
Document Property The Document property sets the file or document that will be used in the Execute method. If this property is blank, the server returns the default document. The syntax is:
MyInetControl.Document = "MyFile.Htm"
Name Property The Name property is the name that the control is called in code (MyInetXfer, for example). VB assigns a default name at the time a control is created, such as Inet1. The name assigned should follow your chosen coding convention. The rules for names require that the name start with a letter and be no longer than 40 characters. It can contain underscore (_) characters, but it cannot contain punctuation, such as commas and periods.
Password Property How a password is used in the Microsoft Internet Transfer Control depends upon the protocol being used. If the protocol is HTTP, the password is not sent with the request because HTTP mostly uses anonymous connections. If the protocol is FTP and these criteria are met--the UserName property is blank, and the Password property is blank--then the control sends the e-mail address of the user. However, if the UserName property has an entry, the control sends the contents of the Password property. The syntax is:
MyInetControl.Password = "aPassWord"
The password is a string; its content and form depend on the system to which it is being attached. Most passwords are case-sensitive, meaning that you must use uppercase and lowercase letters exactly as they appear in the original password that is assigned.
Protocol Property The Protocol property returns or sets the protocol that will be used with the Execute method for the control. The syntax for the Protocol property is:
MyInetControl.Protocol = type
These protocol types are shown in the following enumerated list of integers:
Integer | Value | Description |
icUnknown | 0 | The protocol is unknown |
icDefault | 1 | The default protocol in The Registry is used |
icFTP | 2 | File Transfer Protocol |
icReserved | 3 | Reserved for future use |
icHTTP | 4 | Hypertext Transfer Protocol |
icHTTPS | 5 | Secure Hypertext Transfer Protocol |
Proxy Property If the Access property is set to use a named proxy, the Proxy property is where that name is set. The syntax is:
MyInetControl.Proxy = Myproxy
This also can be the IP address of the proxy server.
RemoteHost Property The RemoteHost property returns or sets the host to which the Internet Transfer Control sends the request. This can be either the remote host domain name--such as ftp.microsoft.com--or the dotted quartet IP address, as in 190.190.28.1. The syntax is:
MyInetControl.RemoteHost = "ftp.microsoft.com"
RemotePort Property The RemotePort property sets or returns the port number to which requests are sent. The Protocol property automatically sets the RemotePort property to a well-known port--if one exists-- such as Port 80 for HTTP or Port 21 for FTP. The syntax is:
MyInetControl.RemotePort = 80
RequestTimeout Property The RequestTimeout property is the time (in seconds) that the control waits for a response before an error is generated. If the request is made with the OpenURL method, an error is generated. If the Execute method is used, a StateChanged event is generated, with the state being an error. Setting the property to 0 indicates infinity. The syntax is:
MyInetControl.RequestTimeout = 20
ResponseCode and ResponseInfo Properties When a request is made of a server, the server might generate an error that is transmitted to the client system. An example is the 404 Not Found error with which you are probably familiar. This is transmitted in two parts: the response code and the response information. These two properties are used by the client system to return this information for display. The syntax is:
MyCode = MyInetControl.ResponseCode MyInfo = MyInetControl.ResponseInfo
StillExecuting Property The StillExecuting property is used to test whether the control is busy. The value is Boolean, with -1 indicating True and 0 equaling False. The syntax is:
If MyInetControl.StillExecuting = -1 Then...
URL Property The URL property sets or returns the URL that is used by the OpenURL or Execute method. The syntax is:
MyInetControl.URL = "http://www.microsoft.com"
UserName Property Whether the UserName property is transmitted to the remote host system depends on the protocol being used. If the protocol is HTTP, no name is transmitted. If the protocol is FTP, a user name is transmitted. If the UserName property is blank, the user name anonymous is sent. The syntax is:
MyInetControl.UserName = "MyName"
Methods are predefined functions that are used to perform various tasks on the control. There are methods that open a connection and methods that retrieve data from a buffer. The methods used with the Microsoft Internet Transfer Control are discussed in the following sections.
Cancel Method The Cancel method cancels the current request and closes all currently open connections. The syntax is:
MyInetControl.Cancel
Execute Method The Execute method sends a request to a remote server. The request must be valid for the specified protocol. The syntax is:
Object.Execute url, operation, data, requestHeaders
Table 40.2 examines the elements of the syntax.
Element | Example | Description |
object | MyInetControl | An object expression that evaluates to the control Name property. |
url | http://www.micro | The Universal Resource Locator to which the control should connect. |
operation | POST | Specifies the operation to be executed. |
data | MyVar: vardata | Contains the data that may be required by the operation. |
requestHeader | Header name: value | Specifies additional headers to be sent by the server. |
GetChunk Method The GetChunk method is used to retrieve data from the buffer that is created by the Internet Transfer Control. The syntax is:
MyInetControl.GetChunk(size,datatype)
size is a long integer and datatype is optional, with the default being text. The other type is a byte array. These types are an enumerated list, as shown in the following table:
Integer | Value | Description |
icString | 0 | Retrieves data as a string |
icByteArray | 1 | Retrieves data as a byte array |
An example of using the GetChunk method is shown in Listing 40.15. The StateChanged event is being used to initiate the use of the GetChunk method.
Private Sub Inet1_StateChanged(ByVal State As Integer) ` Retrieve server response using the GetChunk ` method when State = 12. The example data is text. Select Case State ` ... Other cases not shown. Case icResponseReceived ` 12 Dim MyData As Variant ` Data variable. Dim MystrData As String: MystrData = "" Dim bFinished As Boolean: bFinished = False MyData = Inet1.GetChunk(1024, icString) Do While Not bFinished strData = Data & MyData ` Get next chunk. MyData = Inet1.GetChunk(1024, icString) If Len(vtData) = 0 Then bFinished = True End If Loop txtData.Text = strData End Select End Sub
This Sub would place the data in a text box named txtData.
GetHeader Method The GetHeader method retrieves additional headers from the server. If no header name is specified, then all headers are retrieved. The headers contain such information as the date last modified and the content length. The syntax is:
MyInetControl.GetHeader(headername)
Some of the headers usually available are:
Header | Description |
Date | Contains the time and date of the document's transmission |
MIME-Version | Contains the MIME protocol version |
Server | Contains the server name |
Content-length | The length of the content file (in bytes) |
Content-type | Reveals the MIME content-type |
Last-modified | The time and date the file was last modified |
OpenURL Method The OpenURL method is used to retrieve the document specified in the URL. The syntax is:
object.OpenURL url, datatype
An example of the use of the syntax is:
MyInetControl.OpenURL "http://www.microsoft.com", icString
The following are the data types for the OpenURL method:
Integer | Value | Description |
icString | 0 | Retrieves data as a string |
icByteArray | 1 | Retrieves data as a byte array |
Events are the triggers that invoke the methods. The Microsoft Internet Transfer Control generates only one event, the StateChanged event. The values for the State property usually are used in a Case statement that executes the proper functions based on the State value. The State values are shown in Table 40.3.
Constant | Value | Description |
icNone | 0 | No state to report |
icHostResolvingHost | 1 | The IP address is being resolved by a DNS |
icHostResolved | 2 | The IP address has been resolved |
icConnecting | 3 | The connection to the server is being established |
icConnected | 4 | The connection has been successfully completed |
icRequesting | 5 | The request is being transmitted to the server |
icRequestSent | 6 | The transmission of the request is complete |
icReceivingResponse | 7 | The response from the server is being received |
icResponseReceived | 8 | The response from the server has been successfully received |
icDisconnecting | 9 | The client is disconnecting from the server |
icDisconnected | 10 | The disconnect process is complete |
icError | 11 | An error has occurred in the communication with the server |
icResponseCompleted | 12 | The data requested has been successfully received |
A simple example using the Internet Transfer Control demonstrates how powerful the control is and how easy it is to use. In this example, a new project has been created in Visual Basic. The Microsoft Internet Transfer Control Version 5.0 and the Microsoft RichTextBox Control Version 5.0 have been added to the project.
The following controls have been added on the project form:
Button |
Name | Caption |
|
RichTextBox | RichTextBox1 |
|
Internet Transfer | Inet1 |
|
Command1 | OpenURL |
|
Command2 | GetHeader |
|
Command3 | FTP |
|
Command4 | Cancel |
The arrangement of the controls at design time is shown in Figure 40.7.
FIG. 40.7
Notice that the Microsoft Internet Transfer Control is visible at design time.
The amount of code required to use the control is surprisingly small. Opening a connection to a server and retrieving a file requires only three lines of code, as shown in Listing 40.16. Here, the OpenURL command button was clicked.
Private Sub Command1_Click() RichTextBox1.Text = Inet1.OpenURL("http://www.microsoft.com") End Sub
The results of this connection are shown in Figure 40.8. Notice that the HTML has not been formatted. This is because the file is displayed as transferred.
FIG. 40.8
The display in a rich text box preserves the original file formatting.
The Click event for the GetHeader command button is equally simple and straightforward, as shown in Listing 40.17.
Private Sub Command2_Click() RichTextBox1.Text = Inet1.OpenURL("http://www.microsoft.com") RichTextBox1.Text = Inet1.GetHeader End Sub
The result of Listing 40.17 is displayed in Figure 40.9. The headers are in a header-name: header-data format. In the code, no header name was specified, so all headers were transferred.
The FTP command button specifies a file to be transferred. The file is transferred and displayed, as shown in Figure 40.10; the accompanying code appears in Listing 40.18.
Private Sub Command3_Click() RichTextBox1.Text = Inet1.OpenURL("ftp://ftp.microsoft.com/disclaimer.txt") End Sub
FIG. 40.9
The headers available will vary from server to server.
FIG. 40.10
The text file is displayed as it is formatted.
The final command button, the Cancel button, simply breaks the connection to any server. The code is shown in Listing 40.19.
Private Sub Command3_Click() Inet1.Cancel End Sub
As you can see, the Microsoft Internet Transfer Control is both very easy to use and very powerful. The broad set of properties and methods provides a very detailed level of control when required, but it can also be very simple to use.
The WebBrowser control is the ActiveX control DLL Shdocvw.dll, which is part of Microsoft Internet Explorer. The WebBrowser control can add browsing of documents on the local system or on the Web. It also parses HTML documents and keeps a history log so that you can return to previously displayed documents. Because this control can view richly formatted documents, it can host Excel spreadsheets and Microsoft Word documents. This control needs to be added to the toolbox. It is the Microsoft Internet Controls.
A review of some of the properties, methods, and events of the WebBrowser control will provide insight into some of its possible uses.
A few of the properties are available to be set at design time. Some are read-only at run time and unavailable at design time. Others can be set only at design time and are read-only at run time. But some properties can be set both at run time and at design time.
Important information is contained in the data type of the property. The data type can be a string, an integer, a long integer, or any other data type.
LocationName Property The LocationName property returns the name of the resource that is currently being displayed as a string. The syntax is:
MyVar = MyBrowser.LocationName
LocationURL Property The LocationURL property returns the URL of the resource that is currently displayed as a string. The syntax is:
MyVar = MyBrowser.LocationURL
Type Property The Type property returns the type name of the resource that is currently displayed as a string. The syntax is:
MyVar = MyBrowser.Type
Methods are predefined functions that are used to perform various tasks on the control. For example, there are methods that move forward and backward in the history list. The methods used with the WebBrowser control are discussed in the following sections.
GoBack Method The GoBack method navigates back one item in the history list maintained by the control. The syntax is:
MyBrowser.GoBack
GoForward Method The GoForward method navigates forward one item in the history list maintained by the control. The syntax is:
MyBrowser.GoForward
GoHome Method The GoHome method navigates to the home or start page, as defined in the Internet Explorer Options Dialog box. The syntax is:
MyBrowser.GoHome
GoSearch Method The GoSearch method navigates to the search page, as defined in the Internet Explorer Options Dialog box. The syntax is:
MyBrowser.GoSearch
Navigate Method The Navigate method navigates to the resource identified in the URL parameter of the method. The syntax is:
MyBrowser.Navigate URLVar
Refresh Method The Refresh method reloads the page that is currently displayed by the WebBrowser control. The syntax is:
MyBrowser.Refresh
Stop Method The Stop method cancels any pending navigation, any download operation, and any dynamic page elements, such as animation or background music. The syntax is:
MyBrowser.Stop
Events fire when certain actions take place. The WebBrowser control fires a number of events; these events can be handled to provide functionality for code that is attached to the control. An example is the DownloadComplete event, which can be used to clean up after a file download.
Some events that are generated by the WebBrowser control include the following:
A very simple sample Web browser has been created to show how easy it is to use the WebBrowser control (see Figure 40.11 for the browser as it appears at design time).
FIG. 40.11
The URL is entered in the text box and then the Navigate button is clicked.
The Web Browser consists of a command button with the caption "Navigate," a text box in which you enter the URL, and the WebBrowser control. Figure 40.12 shows the Web Browser when it is first opened. The code activated by the Navigate button is shown in Listing 40.20.
FIG. 40.12
The simplest of all Web browsers is functionally useable.
Private Sub Command1_Click() WebBrowser1.Navigate Text1.Text End Sub
Figure 40.13 shows the WebBrowser displaying the Microsoft Home Page. The WebBrowser control is extremely easy to use and can be controlled at a very detailed level.
FIG. 40.13
Construction of a Web browser is quite simple with the WebBrowser control.
In this chapter, you have examined three controls that can be used in Visual Basic to enable your applications on the Web: the WebBrowser Control, the Internet Transfer Control, and the Winsock Control. These controls are easy to use. The only limit to the applications that you can create for the Web with these controls is your imagination. The following chapters provide additional insight into Web applications:
© Copyright, Macmillan Computer Publishing. All rights reserved.