Skip to main content
 首页 » 编程设计

C# 使用 JavaScript 与浏览器通信

2024年02月23日34lovecherry

如何从 JavaScript 向 C# 应用程序传递消息,我可以在 C# 中使用 PHP 和 tcpListner 来做到这一点(但使用 PHP 需要服务器来托管),我需要本地主机与浏览器通信 C# 应用程序(使用 javaScript 或任何其他可能的方式),浏览器需要将消息传递给运行在同一匹配上的应用程序

你能用样本建议合适的方法吗

请您参考如下方法:

您可以通过以下方式执行此操作。

第 1 步:您必须创建一个监听器。 .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

完成监听部分后,剩下的部分就是处理从请求中检索到的参数。