2

I have created a PHP websocket server script as following.

$socket = socket_create(AF_INET, SOCK_STREAM, 0);
$result = socket_bind($socket, '127.0.0.1', 5001);
while (true) {
    $result = socket_listen($socket);
    $client =  socket_accept($socket);
    $input = socket_read($client, 1024);
    $output = 'Input Received: '.$input;
    socket_write($client, $output, strlen($output));
    socket_close($client);
}
socket_close($socket);

I've executed file containing above code in terminal using following command

$ php server.php

Now I want to get the response on my front-end using JavaScript. I've used following JS snippet but not working.

var ws = new WebSocket("ws://localhost:5001/echo");
ws.onopen = function() {
ws.send("Message to send");
    alert("Message is sent...");
};
ws.onmessage = function (evt) { 
    var received_msg = evt.data;
    alert("Message is received...");
};
ws.onclose = function() { 
    alert("Connection is closed..."); 
};

Receiving following error:

WebSocket connection to 'ws://localhost:5001/echo' failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE

5
  • 3
    You've created a TCP socket, not a websocket. There's a fair bit more to it than that. Commented Aug 6, 2018 at 7:40
  • @BenFortune - how to create websocket (ws) rather than tcp socket? or tcp socket able to fulfil my requirement? Commented Aug 6, 2018 at 7:58
  • 1
    There are plenty of libraries for it.stackoverflow.com/questions/12203443/… Commented Aug 6, 2018 at 8:10
  • @BenFortune - What can I do to make JavaScript communicate with TCP rather than creating websocket using 3rd party libraries. Commented Aug 6, 2018 at 9:14
  • 3
    Nothing. Browsers don't generally support raw TCP connections using JS. You need an abstraction, which is why websockets exist. Commented Aug 6, 2018 at 9:17

1 Answer 1

2

Writing a PHP websocket server requires to perform a certain handshake with the client connecting to you via ws:// . In addition you need to decode and encode messages going in and out. The real fun starts when the clients contact you via wss://, then you have to take care of certificate and key within your PHP server and use stream-io instead of socket-io and so on and on. You can have a look at my implementation of all this and use it as another starting point .

https://github.com/napengam/phpWebSocketServer

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.