Jump to content

First Websocket- What am I doing wrong?


MrFish
 Share

Recommended Posts

I don't have much experience with sockets in general but I'd like to learn how to use these websockets. I will use PHP to setup the server end- though I know PHP is not the most suited for this sort of thing. Instead of using a WebSocket class for PHP I'd like to do it from scratch just to see how it works. The below code is mostly copied-pasted from a tutorial I was looking at-

<?php	    set_time_limit(0);  	    $port = 9011;	    $address = "localhost";	    $sock = socket_create(AF_INET, SOCK_STREAM, 0); 	    socket_bind($sock, $address, $port) or die("Could not bind socket on $port");	    socket_listen($sock);	    echo "listening...\n";  	    $client = socket_accept($sock);	    $input = socket_read($client, 1024);	    $output = ereg_replace("", $input).char(0); 	    socket_write($client, $output);	    socket_close($client);?>

# php -q socket_server.phplistening...

And the JavaScript looks like this-

	    connection = new WebSocket('ws://mysite.net:9011/tests/socket_server.php');	    connection.onopen = function()	    {			    console.log("Connection open!");	    }	    connection.onclose = function()	    {			    console.log("Connection closed");	    }	    connection.onerror = function(e)	    {			    console.log("socket error: " + e);	    }

When I go to this page to test it (on the same server as the php) I get "Connection closed" in the console and nothing else. This happens a few seconds after the page loads. I've opened up port 9011 on the server for all incoming and outgoing TCP/UDP connections. Anyone know what I could be doing wrong?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...