我在下面的代码中创建了一个在listener.GetContext()上等待的HTTPLISTENER。
如何从另一个VB应用程序与此通信?我似乎无法让WebRequest.Create使用我的HTTPLISTENER示例正在使用的URI。来自第二个应用程序的这行代码不起作用:
Dim request As WebRequest = WebRequest.Create(prefixes(0))
以下是代码:
Imports System.Net
Imports System.Globalization
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim prefixes() As String = {"http://*:8080/HttpListener/"}
ProcessRequests(prefixes)
End Sub
Private Sub ProcessRequests(ByVal prefixes() As String)
If Not System.Net.HttpListener.IsSupported Then
Console.WriteLine( _
"Windows XP SP2, Server 2003, or higher is required to " & _
"use the HttpListener class.")
Exit Sub
End If
' URI prefixes are required,
If prefixes Is Nothing OrElse prefixes.Length = 0 Then
Throw New ArgumentException("prefixes")
End If
' Create a listener and add the prefixes.
Dim listener As System.Net.HttpListener = _
New System.Net.HttpListener()
For Each s As String In prefixes
listener.Prefixes.Add(s)
Next
Try
' Start the listener to begin listening for requests.
listener.Start()
Console.WriteLine("Listening...")
' Set the number of requests this application will handle.
Dim numRequestsToBeHandled As Integer = 10
For i As Integer = 0 To numRequestsToBeHandled
Dim response As HttpListenerResponse = Nothing
Try
' Note: GetContext blocks while waiting for a request.
Dim context As HttpListenerContext = listener.GetContext()
' Create the response.
response = context.Response
Dim responseString As String = _
"<HTML><BODY>The time is currently " & _
DateTime.Now.ToString( _
DateTimeFormatInfo.CurrentInfo) & _
"</BODY></HTML>"
Dim buffer() As Byte = _
System.Text.Encoding.UTF8.GetBytes(responseString)
response.ContentLength64 = buffer.Length
Dim output As System.IO.Stream = response.OutputStream
output.Write(buffer, 0, buffer.Length)
Catch ex As HttpListenerException
Console.WriteLine(ex.Message)
Finally
If response IsNot Nothing Then
response.Close()
End If
End Try
Next
Catch ex As HttpListenerException
Console.WriteLine(ex.Message)
Finally
' Stop listening for requests.
listener.Close()
Console.WriteLine("Done Listening...")
End Try
End Sub
End Class
答案 0 :(得分:0)
验证HttpListener实际上正在侦听的最简单方法是导航到您正在使用浏览器监听的URL。如果找不到它,您将收到404错误。
确认侦听器正在运行后,请尝试使用WebClient在代码中与其进行通信。 WebClient的界面比HttpWebRequest简单得多,并且可以为您提供从流中读取和写入的功能。
string result = WebClient.DownloadString("http://google.com");
Console.WriteLine(result);