我使用的是firefox扩展程序,它每次加载新页面时都会检查一次,当它加载时,它会向C#程序中的Web服务器发送握手请求。我的问题是服务器永远不会收到请求。有人可以指出我正确的方向,因为我认为我做错了什么。谢谢
function examplePageLoad(event) {
if (event.originalTarget instanceof HTMLDocument) {
var win = event.originalTarget.defaultView;
if (win.frameElement) {
var socket = new WebSocket('127.0.0.1:13000');
socket.onopen = function() {
alert('handshake successfully established. May send data now...');
};
socket.onclose = function() {
alert('connection closed');
};
}
}
}
window.addEventListener("load", function () {
gBrowser.addEventListener("load", examplePageLoad, true);
}, false);
在C#中:
public void acceptClient()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Event was fired!");
UserModel um = new UserModel();
um.maintainUserModel(); //method uses to maintain user model
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
最佳答案
您在浏览器中使用哪个IP来访问该页面?回送还是本地IP?必须是相同的AFAIK。
在C#中使用回送地址时,无需查找它。只需使用IPAddress.Loopback
即可。
除此之外,您的服务器没有任何问题。
旁注:
um.maintainUserModel(); //method uses to maintain user model
请不要写这样的评论。这只是实际代码的重复。它不会增加任何值,它所做的只是使代码文件困惑。
更新
这个脚本可以很好地连接:
<script type="text/javascript">
function examplePageLoad(event) {
if ("WebSocket" in window) {
var ws = new WebSocket("ws://localhost:13000/");
ws.onopen = function() {
alert('Sending');
ws.send("message to send");
}
ws.onmessage = function (evt) {
alert('Received: ' + evt.data);
};
ws.onclose = function() { // websocket is closed.
};
alert('readystate: ' + ws.readyState + " for " + ws.URL);
}
else
alert('Not supported');
}
if (window.addEventListener) {
window.addEventListener("load", examplePageLoad, true);
}
</script>
关于c# - 从firefox扩展名连接到C#应用程序中的localhost服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5701034/