简体   繁体   中英

how to change client socket javascript to client socket php

I have a client socket with javacscript as below. How to convert it to PHP, so that it can receive data from the server socket

Note: I'm using PHP socket Bloatless. https://github.com/bloatless/php-websocket

This Client Javascript :

<script>
 // connect to chat application on server
let serverUrl = 'ws://127.0.0.1:8000/chat';
let socket = new WebSocket(serverUrl);

// log new messages to console
socket.onmessage = (msg) => {
    let response = JSON.parse(msg.data);
    console.log(response.data);
};
</script>

To connect a PHP socket to a JavaScript client:

  • you have to perform a handshake
  • then the conversation can begin

I can show you how I perform the handshake as well as the decoding from the client to the server (JS->PHP)

But I can't receive messages from the server to the client (PHP->JS) the client closes I've already opened the topic but I didn't get an answer.

Reading from and writing to a websocket from PHP requires you to follow the rules layed out in RFC6455 . That means performing a handhsake with the server, encode and decode the payload in frames among other things. In Javascript this is already done for you under the hood.

You can have a look at such PHP client in https://github.com/napengam/phpWebSocketServer/blob/master/phpClient/websocketCore.php

Examples on how to use this client are given in directory websocketExtern.

Please keep in mind that php does not behave like JavaScript with reagrds to callbacks , events and such.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM