Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 110 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
110
Dung lượng
5,72 MB
Nội dung
context.Response.StatusCode = 404 End Select End While End Sub Our background task performs its work in a loop as long as the HttpListener is actively lis- tening. Every developer knows that performing a set of tasks in a (relatively) tight loop is dan- gerous, possibly leading to computer or application lockup. However, the BackgroundWorker performs this on another thread, leaving our application responsive. For this application, we first get access to the context for the listener. The context groups together one client’s set of communication with our listener. Similar to the HttpContext in ASP.NET, the HttpListenerContext provides access to the HttpListenerRequest and HttpListenerResponse objects, so the first step in handling a request should always be to get this context. Next, the code uses a very simple means of determining the request URL. In a more full-featured implementation, this could be more complex, separating any query values from the path requested, etc. For this sample, the listener only responds to three main paths, “/time”, “/date”, and “/random” to receive the current (server) time or date, or a random Integer value. If the user requests anything else, we return a 404. 7. The SendPage subroutine simply writes out a basic HTML page, and the value determined. Private Sub SendPage(ByVal response As HttpListenerResponse, _ ByVal message As String) Dim sb As New StringBuilder ‘build string With sb .Append(“<html><body>”) .AppendFormat(“<h3>{0}</h3>”, message) .Append(“</body></html>”) End With Me.EventLog.WriteEntry(sb.ToString) ‘set up content headers With response .ContentType = “text/html” .ContentEncoding = Encoding.UTF8 .ContentLength64 = sb.ToString.Length Me.EventLog.WriteEntry(sb.ToString.Length.ToString) Try Using writer As New StreamWriter(.OutputStream) With writer .Write(sb.ToString) .Flush() End With End Using Catch ex As Exception Me.EventLog.WriteEntry(ex.Message, EventLogEntryType.Error) 958 Chapter 26 29_575368 ch26.qxd 10/7/05 11:22 PM Page 958 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Finally ‘close the response to end .Close() End Try End With End Sub Hopefully there isn’t much surprising in this code. Using a StringBuilder, a response is built. Then the content is written back to the browser (see Figure 26-8) using a StreamWriter that is created on top of the Response.OutputStream. Remember to Close the Response, or the request will never close until it times out. Figure 26-8 8. Before you can install and test your Windows Service, however, it must be installed. On the Properties window for the actual service, click Add Installer (see Figure 26-9). This adds a new file to the project called ProjectInstaller.vb, and adds two components to the file, ServiceInstaller1 and ServiceProcessInstaller1. You can either keep these names or change them as you desire. In addition, set the properties as in the following table. Figure 26-9 959 Network Programming 29_575368 ch26.qxd 10/7/05 11:22 PM Page 959 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Component Property Value ServiceInstaller1 Description Sample Service from Wrox Professional Visual Basic 2005 DisplayName Sample Service ServiceName SampleService ServiceProcessInstaller1 Account LocalSystem Most of these properties only affect the display values for the Windows Service. However, the Account property of the ServiceProcessInstaller deserves special mention. Windows Services run on behalf of the user. Therefore, they can actually run under another user account. By setting the Account property to LocalSystem, you are setting the resulting Windows Service to run under the local system account. This account has a lot of access to the system, so you may want to instead use an account with more limited rights to the system; however you would have to create this account separately. 9. Build the Windows service. Unfortunately, if you attempt to run the service directly from Visual Basic, you will get an error message (see Figure 26-10). Figure 26-10 A Windows Service can only run if it has been installed into the system, and this task is per- formed using a command-line utility InstallUtil.exe. Open the Visual Studio Command Prompt and navigate to the directory where you have built MiniServer.exe. Run installutil miniserver.exe , and hopefully you’ll be greeted with a success message (see Figure 26-11). 960 Chapter 26 29_575368 ch26.qxd 10/7/05 11:22 PM Page 960 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 26-11 10. Finally, you can start your new service. Open the Services application from Start ➪ All Programs➪ Administrative Tools. Find the Sample Service in the list (see Figure 26-12), and click Start. You should now be able to request one of the items the service is listening to, such as http://local host:9090/time (see Figure 26-13). 961 Network Programming 29_575368 ch26.qxd 10/7/05 11:22 PM Page 961 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 26-12 Figure 26-13 Just to confirm that all of the Prefixes work, you can also request one of the values using the vroot rather than using the port (see Figure 26-14). 962 Chapter 26 29_575368 ch26.qxd 10/7/05 11:22 PM Page 962 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 26-14 The HttpListener adds yet another powerful way for your applications to communicate. It gives you the ability to extend the reach of your applications out to Web browser clients, without requiring the additional administrative and management overhead of IIS to your deployment. Summary Programming directly to the network provides a great deal of power and flexibility. Of course, all of that power and flexibility comes at a cost. Many of the services provided by higher-level technologies, such as Web Services or Remoting, aren’t available, and must often be re-created. However, in those situations where you must communicate with an existing application, or when you need the ultimate in control and speed, using the classes in System.Net make life easier than it would be otherwise. This chapter looked at many of the classes that expose network programming. You’ve seen how to make Web requests without a browser, so you could use the data on the Internet in your applications; you’ve seen how you can leverage the bare sockets layer to write your own communication protocols, and finally, you’ve seen some of the new classes in Visual Basic 2005 for creating FTP clients and Web servers. 963 Network Programming 29_575368 ch26.qxd 10/7/05 11:22 PM Page 963 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 29_575368 ch26.qxd 10/7/05 11:22 PM Page 964 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Visual Basic and the Internet In today’s network-centric world, it’s very likely that applications will need to work with other computers over a private network, the Internet, or both. This chapter details how to: ❑ Download resources from the Web ❑ Design your own communication protocols ❑ Reuse Internet Explorer in your applications A good place to start working with network resources is with a look at how to download content from the Web. Downloading Internet Resources Downloading content from the Web is very easy, so you’ll throw together a basic application before getting onto some more meaty topics. This application will download HTML from a Web page and display it in a text box. Later on, you’ll look at how you can display HTML properly by hosting Internet Explorer (IE) directly using the new WebBrowser control in Windows Forms applications, but for now you’ll just use plain text. In order to download a Web page, you need to be able to identity the remote page that you wish to download, make a request of the Web server that can provide that page, listen for the response, and download the data for the resource. 30_575368 ch27.qxd 10/7/05 11:24 PM Page 965 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The relevant classes for this example are System.Uri, System.Net.WebRequest, System.Net .HttpWebRequest , and System.Net.HttpWebResponse: ❑ System.Uri is a useful general-purpose class for expressing a Uniform Resource Identifier (URI). A Uniform Resource Locator (URL) is a type of URI (although in reality the terms are so confused that they are often used interchangeably). A URI, however is “more than” a URL, which is why this .NET class is Uri and not Url. System.Uri has many properties for decoding a URI. For example, if you had a string like www.pretendcompany.com:8080/ myservices/ myservice.asmx?WSDL , you could use the Port property to extract the port number, the Query property to extract the query string, and so on. ❑ A WebRequest expresses some kind of Internet resource whether it is located on the LAN or WAN (so in my opinion a better name for this class would be NetRequest, as the classes aren’t specifically related to the Web protocol). ❑ Protocol-specific descendants of WebRequest carry out the actual request: HttpWebRequest expresses an HTTP download and FileWebRequest expresses a file download, for example file://c:/MyFile.txt. ❑ An HttpWebResponse is returned once a connection to the Web server has been made and the resource is available to download. There are another two major classes related to working with the Internet in the .NET Framework. One is System.Net.WebClient and the other is System.Net.WebProxy. WebClient is basically a helper class that wraps the request and response classes previously mentioned. As this is a professional-level book, I’m going to show you what to do behind the scenes, in effect, reengineer what WebClient can do. I’ll talk about WebProxy later, which allows you to explicitly define a proxy server to use for Internet communications. Let’s use these classes to build an application. Create a new Windows application, create a new form, and add controls to it as shown in Figure 27-1. Figure 27-1 The control names are: textUrl, buttonGo, and textData. The Anchor properties of the controls are set so that the form resizes properly. The control textUrl should be set to Top, Left, Right; buttonGo to Top, Right; and textData to Top, Left, Bottom, Right. 966 Chapter 27 30_575368 ch27.qxd 10/7/05 11:24 PM Page 966 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Add these namespace import declarations to the form’s code: Imports System.IO Imports System.Net Imports System.Text To keep the code simple, you’ll include all the functionality into the Click handler of buttonGo. In an ideal world, you want to break the code in the handler out to a separate method. This enriches the inter- face of the object and promotes good reuse. The first thing you do here is create a new System.Uri based on the URL that the user enters into the text box: Private Sub buttonGo_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles buttonGo.Click Dim uri As New Uri(textUrl.Text) Then, you’ll illustrate some of the useful properties of System.Uri: Dim builder As New StringBuilder builder.Append(“AbsolutePath: “ & uri.AbsolutePath & VbCrLf) builder.Append(“AbsoluteUri: “ & uri.AbsoluteUri & VbCrLf) builder.Append(“Host: “ & uri.Host & VbCrLf) builder.Append(“HostNameType: “ & uri.HostNameType.ToString() & _ VbCrLf) builder.Append(“LocalPath: “ & uri.LocalPath & VbCrLf) builder.Append(“PathAndQuery: “ & uri.PathAndQuery & VbCrLf) builder.Append(“Port: “ & uri.Port & VbCrLf) builder.Append(“Query: “ & uri.Query & VbCrLf) builder.Append(“Scheme: “ & uri.Scheme) MsgBox(builder.ToString()) The shared Create method of System.Net.WebRequest is used to create the actual object that you can use to download the Web resource. Notice how you don’t create an instance of HttpWebRequest; you’re working with a return object of type WebRequest. However, you’ll actually be given an HttpWebRequest object, and WebRequest chooses the most appropriate class to return based on the URI. This allows you to build your own handlers for different network resources that can be used by consumers who simply sup- ply an appropriate URL. To make the request and get the response back from the server (so ultimately you can access the data), you call the GetResponse method of WebRequest. In your case, you’ll get an HttpWebResponse object — once more it’s up to the implementation of the WebRequest-derived object, in this case HttpWebRequest, to return an object of the most suitable type. If the request is not okay, you’ll get an exception (which for the sake of simplicity you won’t bother pro- cessing). If the request is okay, you can get the length and the type of the response using properties of the WebResponse object: Dim request As WebRequest = WebRequest.Create(uri) Dim response As WebResponse = request.GetResponse() builder = New StringBuilder 967 Visual Basic and the Internet 30_575368 ch27.qxd 10/7/05 11:24 PM Page 967 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... builder.Append(“Request type: “ & request.GetType().ToString() & VbCrLf) builder.Append(“Response type: “ & response.GetType().ToString() & VbCrLf) builder.Append(“Content length: “ & response.ContentLength & _ PDF Merge “ bytes” & VbCrLf) and Split Unregistered Version - http://www.simpopdf.com builder.Append(“Content type: “ & response.ContentType & VbCrLf) MsgBox(builder.ToString()) It just remains for you... the application as shown in Figure 2 7-3 provides information about the response 968 Visual Basic and the Internet Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 2 7-3 Finally, you get to see the response data itself as illustrated in Figure 2 7-4 Figure 2 7-4 Perhaps the most important exception to be aware of when using these classes is the System.Net WebException exception... As Integer = 101 01 Next, open the designer file for Form1 (Form1.Designer .vb) and add this code to the constructor that populates the field and changes the caption: 970 Visual Basic and the Internet _ Public Sub New() MyBase.New() Simpo PDF Merge and‘This call is requiredVersionWindows Form Designer Split Unregistered by the - http://www.simpopdf.com InitializeComponent()... direction ‘ Split the window Simpo PDF Merge andUpdate Unregistered Version - http://www.simpopdf.com UpdateCaption() End Sub Protected Sub UpdateCaption() ‘ Set the text Dim builder As New StringBuilder(_username) builder.Append(“ - “) builder.Append(_direction.ToString()) builder.Append(“ - “) builder.Append(Thread.CurrentThread.GetHashCode()) builder.Append(“ - “) If Not _client Is Nothing Then... the new Conversation form This needs three TextBox controls (textUsername, textMessages, and textMessage) and a Button control (buttonSend) The form is PDF Merge and Split Unregistered Version - http://www.simpopdf.com shown in Figure 2 7-6 Figure 2 7-6 This class requires a number of fields and an enumeration It needs fields to hold the username of the user (which you’ll default to Evjen), the underlying... mainThreadId = System.Threading.Thread.CurrentThread.GetHashCode() Text &= - & _mainThreadId.ToString() End Sub Note that you can get to the Form1.Designer .vb file by starting from the Form1 .vb file and using Visual Studio by selecting Form1 and New in the uppermost drop-downs in the document window This will cause the Form1.Designer .vb file to open for you To listen for incoming connections, you’ll create... Unregistered Simpo PDF Merge and Split = False Then Version - http://www.simpopdf.com ‘ Create and call Dim args(0) As Object args(0) = ex Invoke(New HandleInitiateConnectionExceptionDelegate(AddressOf _ HandleInitiateConnectionException), args) ‘ return Return End If ‘ Show it MsgBox(ex.GetType().ToString() & “:” & ex.Message) End Sub The result is that when the call comes in from the thread-pool-managed thread,... Chapter 27 If you run the project now, you should be able to click the Connect button and see two windows — one inbound and one outbound, as shown in Figure 2 7-7 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 2 7-7 If you close all three windows, the application will keep running because you haven’t written code to close down the listener thread, and having an open thread... connect and exchange messages, as shown in Figure 2 7-8 Note that the screen shots show the username of the inbound connection as Tuija This was done with the textUsername text box so that you can follow which half of the conversation comes from where 985 Chapter 27 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 2 7-8 Shutting Down the Application You’ve yet to solve... will see a message): Simpo PDF Protected Sub Split Unregistered Version - http://www.simpopdf.com Merge and TransmitThreadEntryPoint() ‘ Create a formatter Dim formatter As New BinaryFormatter Dim workQueue As New Queuevs ‘ name Thread.CurrentThread.Name = “Tx-” & _direction.ToString() ‘ Loop Do While True ‘ Wait for the signal Thread.Sleep (100 0) ‘ Disconnected? If _socket Is Nothing . message (see Figure 2 6-1 1). 960 Chapter 26 29_575368 ch26.qxd 10/ 7/05 11:22 PM Page 960 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 2 6-1 1 10. Finally, you can. error message (see Figure 2 6-1 0). Figure 2 6-1 0 A Windows Service can only run if it has been installed into the system, and this task is per- formed using a command-line utility InstallUtil.exe 2 6-1 3). 961 Network Programming 29_575368 ch26.qxd 10/ 7/05 11:22 PM Page 961 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 2 6-1 2 Figure 2 6-1 3 Just to confirm that all of the