Reputation: 2807
I am using a firefox extension, that checks each time when a new page loads, and when it does, it sends a handshake request to a web server I have in my C# program. My problem is that the server never receives the request. Can someone point me in the right direction since I think I am doing something wrong. Thanks
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);
And in 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();
}
}
Upvotes: 1
Views: 654
Reputation: 101150
Which IP do you use in the browser to get to that page? Loopback or the local IP? Must be the same AFAIK.
When using loopback adress in C#, you do not need to look it up. Just use IPAddress.Loopback
.
other than that, theres nothing wrong with your server.
A side note:
um.maintainUserModel(); //method uses to maintain user model
Please do not write comments like that. It's just a duplication of the actual code. It doesn't add any value, all it do is cluttering the code file.
This script connects fine:
<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>
Upvotes: 1