【问题标题】:C# communication with browser using JavaScript使用 JavaScript 与浏览器进行 C# 通信
【发布时间】:2012-04-24 22:13:39
【问题描述】:
如何从 JavaScript 将消息传递给 C# 应用程序,我可以在 c# 中使用 PHP 和 tcpListner 来做到这一点(但使用 PHP 需要服务器托管),我需要 localhost 与浏览器通信 c# 应用程序(使用 javaScript 或任何其他可能的方式),浏览器需要将消息传递给在同一匹配项上运行的应用程序
您能否通过示例为此建议适当的方法
【问题讨论】:
标签:
c#
javascript
serial-port
tcplistener
【解决方案1】:
您可以通过以下方式做到这一点。
第 1 步:您必须创建一个 Listener。 .net 中的 TcpListener 类或 HttpListener 可用于开发监听器。这段代码展示了如何实现一个 TCP 监听器。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
//Author : Kanishka
namespace ServerSocketApp
{
class Server
{
private TcpListener tcpListn = null;
private Thread listenThread = null;
private bool isServerListening = false;
public Server()
{
tcpListn = new TcpListener(IPAddress.Any,8090);
listenThread = new Thread(new ThreadStart(listeningToclients));
this.isServerListening = true;
listenThread.Start();
}
//listener
private void listeningToclients()
{
tcpListn.Start();
Console.WriteLine("Server started!");
Console.WriteLine("Waiting for clients...");
while (this.isServerListening)
{
TcpClient tcpClient = tcpListn.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(handleClient));
clientThread.Start(tcpClient);
}
}
//client handler
private void handleClient(object clientObj)
{
TcpClient client = (TcpClient)clientObj;
Console.WriteLine("Client connected!");
NetworkStream stream = client.GetStream();
ASCIIEncoding asciiEnco = new ASCIIEncoding();
//read data from client
byte[] byteBuffIn = new byte[client.ReceiveBufferSize];
int length = stream.Read(byteBuffIn, 0, client.ReceiveBufferSize);
StringBuilder clientMessage = new StringBuilder("");
clientMessage.Append(asciiEnco.GetString(byteBuffIn));
//write data to client
//byte[] byteBuffOut = asciiEnco.GetBytes("Hello client! \n"+"You said : " + clientMessage.ToString() +"\n Your ID : " + new Random().Next());
//stream.Write(byteBuffOut, 0, byteBuffOut.Length);
//writing data to the client is not required in this case
stream.Flush();
stream.Close();
client.Close(); //close the client
}
public void stopServer()
{
this.isServerListening = false;
Console.WriteLine("Server stoped!");
}
}
}
第 2 步:您可以将参数作为 GET 请求传递给创建的服务器。您可以使用 JavaScript 或 HTML 表单来传递参数。 jQuery 和 Dojo 等 JavaScript 库将使 ajax 请求更容易。
http://localhost:8090?id=1133
您必须修改上述代码以检索作为 GET 请求发送的参数。
我建议使用 HttpListener 而不是 TcpListener
完成监听部分后,剩下的部分只是处理从请求中检索到的参数。
【解决方案2】:
您应该使用HttpListener 类,或创建一个自托管的 ASP.Net Web API 项目。