[英]C# communication with browser using JavaScript
如何从JavaScript传递消息到C#应用程序,我可以用c#中的PHP和tcpListner(但使用PHP需要服务器来托管),我需要localhost与浏览器通信c#应用程序(使用javaScript或任何其他可能的方式) ,浏览器需要将消息传递给运行在同一个matchine上的应用程序
你能用样品建议适当的方法吗?
您可以通过以下方式执行此操作。
第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
一旦完成了监听部分,休息部分就是处理从请求中检索的参数。
您应该使用HttpListener
类,或者创建一个自托管的ASP.Net Web API项目。
我想你需要像Comet 这样的东西, 请使用Comet查看这个例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.