【发布时间】:2021-12-30 08:29:15
【问题描述】:
我正在尝试创建一个能够访问客户端本地资源的 webapp。
即我打算将exe安装到客户的计算机上。我想通过 JavaScript 代码(在远程服务器上)触发这个 exe 的函数,并触发一个连接到串行端口、读取数据并将该数据返回到网页的函数。
我可以为客户端应用程序编写 C# 或 Visual Basic。
到目前为止,我能够通过 XMLHttpRequest 获得一些结果。我用 C# 打开了端口 9091,并能够通过将 localhost:9091 写入浏览器的地址栏来连接该端口并获取数据,但我无法使用 JavaScript 来完成。 (出现 CORS 错误)
用我的技能可以完成这项任务吗?
客户端应用示例
Imports System.Net
Imports System.Globalization
Imports System.Collections.Specialized
Module HttpListener
Sub Main()
Dim prefixes(0) As String
prefixes(0) = "http://*:9091/"
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 IncMessage As New NameValueCollection
IncMessage = context.Request.QueryString
Dim Field As String
Dim FValue As String
Dim Values() As String
For Each key As String In IncMessage.Keys
Values = IncMessage.GetValues(key)
Field = key
For Each value In Values
FValue = value
MsgBox(Field & " equals " & FValue)
Next value
Next key
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 Module
【问题讨论】:
-
那么您认为浏览器让任意网站在客户端计算机上运行任意二进制文件是一件安全的事情吗?你要做的是写一个浏览器插件。或者让您的程序直接与服务器通信。
-
"javascript which is on remote server",是的,它可能是从远程服务器加载的,但它是在浏览器上下文中执行的。不,您不能从浏览器中的 javascript 访问任何本地资源。特别是你不能只启动一些随机的可执行文件......那将是一个巨大的安全漏洞......
-
javascript code (which is in remote server)...除非你的意思是nodeJS然后Javascript在浏览器中运行,而不是服务器。但在任何一种情况下,您都无法让 Web 应用程序执行本地脚本。正如其他人所说,这将是一场彻底的安全灾难。我们不再拥有像 ActiveX 这样的东西是有原因的! -
您可以在操作系统中注册自定义协议,并让用户单击 Web 应用程序中的链接,然后启动桌面应用程序 - 很像用于在您的桌面上打开 Zoom 和 Teams 通话以及其他类似内容的链接。
-
为什么不编写一个应用程序,通过 HTTP Web 服务(REST 或其他)与与 Web 服务器相同的服务器进行通信。应用程序将数据发送到服务。 Web 服务器(或客户端)从服务中获取数据。是否有您认为需要的实时通信的特定需求?这似乎是寻找问题的解决方案。
标签: javascript c# vb.net