Wednesday 15 July 2015

php - How to receive web socket message from server in client side by html5 socket api -


I have been fighting web sockets for a few days but, so far I could not be able to catch it.

I manage to create a server side file via PHP which is sending messages to a particular address + port but when I try to access that socket in the client side of the HTML5 Socket API I'm not, I'm not able to get it.

Here is my server side PHP cile code.

  $ address = "127.0.0.1"; $ Service_port = 80; Error_reporting (E_ALL); / * Create a TCP / IP socket * / $ socket = socket_create (AF_INET, SOCK_STREAM, SOL_TCP); If ($ socket === false) {echo "socket_cent () failed: reason:". Socket_strerror (socket_last_error ()). "\ N"; } Echo "port '$ service_port' Try to connect to '$ address' ..."; $ Result = socket_connect ($ socket, $ address, $ service_port); If ($ result === false) {echo "socket _connect () failed. \ N Reason: ($ result)". Socket_strerror (socket_last_error ($ socket)) "\ N"; } $ IN = "HEAD / HTTP / 1.1 \ r \ n"; IN $ = "host: www.google.com \ r \ n"; IN $ = "Connection: Close \ r \ n \ r \ n"; $ Out = ''; Echo "Sending HTTP HEAD request ..."; If (! Socket_write ($ socket, IN $, strlen (IN $ IN)) $ $ errorcode = socket_last_error (); $ Errormsg = socket_strerror ($ errorcode); Dying ("Could not send message to socket: [$ errorcode] $ errormsg \ n"); } Echo "OK. \ N";   

On my client side, I am using the following code.

  & lt; Script type = "text / javascript" & gt; // Open a Web Socket var ws = new WebSocket ("ws: //127.0.0.1: 80 /"); Ws.onopen = function () {// Web Socket is connected, send data by sending (ws.send) ("send message"); Warning ("Message is sent ..."); }; Ws.onmessage = function (evt) {var receive_msg = evt.data; Warning ("Message received ..."); }; Ws.onclose = function () {// websocket is closed. Warning ("The connection is closed ..."); }; & Lt; / Script & gt; Resonant "read the reaction: \ n \ n"; While ($ out = socket_read ($ socket, 2048)) {echo "<

$ out


"; } Socket_close ($ socket);

But, I can not be able to get server side messages using this javascript.

This is the first time that I am trying to put my hand in web sockets. So, I do not know exactly how to do it. I also look a lot on Google but can not figure out where and amp; Am I doing wrong?

Regards

It is better to use the second port above 1024 because 1024 Internal port requires root privilege, and this port you use already tries to use for Internet services:

  $ telnet servername portNumber   

Test under a shell or CMD and then you can try to use the websocket object.

No comments:

Post a Comment