当前位置: 首页 > 编程语言 > C#

在C#中使用JavaScript与浏览器通信分享

时间:2023-04-10 20:04:31 C#

在C#中使用JavaScript与浏览器通信PHPneedsservertohost),Ineedlocalhosttocommunicatec#applicationwithbrowser(usingjavaScriptoranyotherpossibleway)),浏览器需要将消息传递给在同一个匹配上运行的应用程序你能用示例适当的方法建议吗?您可以通过以下方式执行此操作。第1步:您必须创建一个侦听器。可以使用.net中的TcpListener类或HttpListener开发监听器。此代码显示如何实现TCP侦听器。使用系统;使用System.Collections.Generic;使用System.Linq;使用系统文本;使用System.Net.Sockets;使用System.Net;使用系统线程;//作者:KanishkanamespaceServerSocketApp{classServer{privateTcpListenertcpListn=null;私有线程listenThread=null;privateboolisServerListening=false;publicServer(){tcpListn=newTcpListener(IPAddress.Any,8090);listenThread=newThread(newThreadStart(listeningToclients));this.isServerListening=true;listenThread.Start();}//listenerprivatevoidlisteningToclients(){tcpListn.Start();Console.WriteLine("服务器启动!");Console.WriteLine("等待客户...");while(this.isServerListening){TcpClienttcpClient=tcpListn.AcceptTcpClient();ThreadclientThread=newThread(newParameterizedThreadStart(handleClient));clientThread.Start(tcpClient);}}//客户端处理器privatevoidhandleClient(objectclientObj){TcpClientclient=(TcpClient)clientObj;Console.WriteLine("客户端已连接!");NetworkStream流=client.GetStream();ASCIIEncodingasciiEnco=newASCIIEncoding();//从客户端读取数据byte[]byteBuffIn=newbyte[client.ReceiveBufferSize];intlength=stream.Read(byteBuffIn,0,client.ReceiveBufferSize);StringBuilderclientMessage=newStringBuilder("");clientMessage.Append(asciiEnco.GetString(byteBuffIn));//向客户端写入数据//byte[]byteBuffOut=asciiEnco.GetBytes("Helloclient!n"+"Yousaid:"+clientMessage.ToString()+"nYourID:"+newRandom().Next());//stream.Write(byteBuffOut,0,byteBuffOut.Length);//在这种情况下不需要向客户端写入数据stream.Flush();stream.Close();客户端.Close();//关闭客户端}publicvoidstopServer(){this.isServerListening=false;Console.WriteLine("服务器已停止!");}}}步骤2:您可以将参数作为GET请求传递给创建的服务器您可以使用JavaScript或HTML形式传递参数。jQuery和Dojo等JavaScript库可以更轻松地生成ajax请求。http://localhost:8090?id=1133您必须修改以上代码以检索作为GET请求发送的参数。我建议使用HttpListener而不是TcpListener一旦侦听部分完成,其余部分将处理从请求中检索到的参数。您应该使用HttpListener类,或创建一个自承载的ASP.NetWebAPI项目。我觉得你需要像Comet这样的东西,请用Comet看看上面这个例子是C#学习教程:UsingJavaScripttocommunicatewiththebrowserinC#分享所有内容,如果对大家有用需要进一步了解C#学习教程,希望大家多多关注—本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: