質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
WebSocket

WebSocketとは双方向・全二重コミュニケーションのためのAPIでありプロトコルのことを指します。WebSocketはHTML5に密接に結びついており、多くのウェブブラウザの最新版に導入されています。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Q&A

解決済

2回答

6986閲覧

【Websocketエラー】WebSocket connection to 'ws:~

ryouya

総合スコア14

WebSocket

WebSocketとは双方向・全二重コミュニケーションのためのAPIでありプロトコルのことを指します。WebSocketはHTML5に密接に結びついており、多くのウェブブラウザの最新版に導入されています。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

0グッド

1クリップ

投稿2021/08/07 08:55

お世話になっております。
下記知見のある方がいらっしゃいましたら、ご教示お願いいたします。

#起きている問題

WebSocket connection to 'ws://localhost:8080/' failed:

websocketでブラウザを動かしたいのですが、
上記エラーが発生し、正常に稼働しません。

#試したこと

https://www.fixes.pub/program/388275.html

上記のサイトを参考に、wss://localhost:8080/(index.html:112)に修正し実行しましたが、
結果は変わりませんでした。

#実行ファイル

#index.html <!DOCTYPE html> <html lang="ja"> <meta charset="utf-8"> <title>Chat</title> <style> .container { width: 600px; } .box { overflow: hidden; } .left { background-color: #D3D3D3; padding: 20px; margin: 5px; width: 300px; float: left; } .right { background-color: #ADFF2F; padding: 20px; margin: 5px; width: 300px; float: right; } </style> <script src="http://code.jquery.com/jquery-2.2.4.js"></script> <script> (function($) { var settings = {}; var methods = { init: function(options) { settings = $.extend({ 'uri': 'ws://localhost:8080', 'conn': null, 'message': '#message', 'display': '#display' }, options); $(settings['message']).keypress(methods['checkEvent']); $(this).chat('connect'); }, checkEvent: function(event) { if (event && event.which == 13) { var message = $(settings['message']).val(); if (message && settings['conn']) { settings['conn'].send(message + ''); $(this).chat('drawText', message, 'right'); $(settings['message']).val(''); } } }, connect: function() { if (settings['conn'] == null) { settings['conn'] = new WebSocket(settings['uri']); settings['conn'].onopen = methods['onOpen']; settings['conn'].onmessage = methods['onMessage']; settings['conn'].onclose = methods['onClose']; settings['conn'].onerror = methods['onError']; } }, onOpen: function(event) { $(this).chat('drawText', 'サーバに接続', 'left'); }, onMessage: function(event) { if (event && event.data) { $(this).chat('drawText', event.data, 'left'); } }, onError: function(event) { $(this).chat('drawText', 'エラー発生!', 'left'); }, onClose: function(event) { $(this).chat('drawText', 'サーバと切断', 'left'); settings['conn'] = null; setTimeout(methods['connect'], 1000); }, drawText: function(message, align = 'left') { if (align === 'left') { var inner = $('<div class="left"></div>').text(message); } else { var inner = $('<div class="right"></div>').text(message); } var box = $('<div class="box"></div>').html(inner); $('#chat').prepend(box); }, }; // end of methods $.fn.chat = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist'); } } // end of function })(jQuery); $(function() { $(this).chat({ 'uri': 'ws://localhost:8080', 'message': '#message', 'display': '#chat' }); }); </script> </head> <body> <input type="text" id="message" size="50" /> <div id="chat" class="container"></div> </body> </html>
#chat-server.php <?php namespace htdocs; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class Chat implements MessageComponentInterface { protected $clients; public function __construct() { $this->clients = new \SplObjectStorage(); } public function onOpen(ConnectionInterface $conn) { // Store the new connection to send messages to later $this->clients->attach($conn); echo "New connection! ({$conn->resourceId})\n"; } public function onMessage(ConnectionInterface $from, $msg) { $numRecv = count($this->clients) - 1; echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n", $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's'); foreach ($this->clients as $client) { if ($from !== $client) { // The sender is not the receiver, send to each client connected $client->send($msg); } } } public function onClose(ConnectionInterface $conn) { // The connection is closed, remove it, as we can no longer send it messages $this->clients->detach($conn); echo "Connection {$conn->resourceId} has disconnected\n"; } public function onError(ConnectionInterface $conn, \Exception $e) { echo "An error has occurred: {$e->getMessage()}\n"; $conn->close(); } }
#Chat.php <?php namespace htdocs; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class Chat implements MessageComponentInterface { protected $clients; public function __construct() { $this->clients = new \SplObjectStorage(); } public function onOpen(ConnectionInterface $conn) { // Store the new connection to send messages to later $this->clients->attach($conn); echo "New connection! ({$conn->resourceId})\n"; } public function onMessage(ConnectionInterface $from, $msg) { $numRecv = count($this->clients) - 1; echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n", $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's'); foreach ($this->clients as $client) { if ($from !== $client) { // The sender is not the receiver, send to each client connected $client->send($msg); } } } public function onClose(ConnectionInterface $conn) { // The connection is closed, remove it, as we can no longer send it messages $this->clients->detach($conn); echo "Connection {$conn->resourceId} has disconnected\n"; } public function onError(ConnectionInterface $conn, \Exception $e) { echo "An error has occurred: {$e->getMessage()}\n"; $conn->close(); } }

#GitHub

https://github.com/karirin/chat_app

#参考

http://challenge.no1s.biz/programming/php/158

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

自己解決

自己解決しました。
Chat.phpのパス先を変更したところ、正常に稼働しました。

before:htdocs/Chat.php

after:htdocs/src/MyApp/Chat.php

投稿2021/08/29 08:45

ryouya

総合スコア14

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

サーバが正しく起動していますか? 参考サイトでも

$ php bin/server.php &

とサーバを起動する手順が書かれていますが、こちらの手順が間違っていればconnection faildが出ると思います。実行環境が書かれていないのでアドバイスができませんが、PHPプログラムのプロセスが永続的に立ち上がってることを確認してください(Linuxならpsコマンドなどで確認可能)。

あとはlocalhostを指定しているので、PHPプログラムとHTML、JSが同じサーバにあることが必須ですが、こちらも問題ないか確認された方が良いと思います。localhostで繋がらないなら127.0.0.1で接続してみると繋がる可能性もあります。

投稿2021/08/09 13:48

AbeTakashi

総合スコア4512

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

ryouya

2021/08/21 04:14 編集

ご回答ありがとうございます! また、連絡遅れてしまい申し訳ございません。 承知しました、本件確認してみます。
ryouya

2021/08/22 07:32

『$ php bin/server.php &』こちらのコマンドを実施したところ、下記エラーが発生しました。 ``` ryouya@DESKTOP-FRGSG5L c:\xampp\htdocs # php bin/chat-server.php & PHP Fatal error: Uncaught Error: Class 'htdocs\Chat' not found in C:\xampp\htdocs\bin\chat-server.php:10 Stack trace: #0 {main} thrown in C:\xampp\htdocs\bin\chat-server.php on line 10 Fatal error: Uncaught Error: Class 'htdocs\Chat' not found in C:\xampp\htdocs\bin\chat-server.php:10 Stack trace: #0 {main} thrown in C:\xampp\htdocs\bin\chat-server.php on line 10 ``` Chatクラスは下記ファイルで宣言しているのですが、エラーが発生してしまいます。 ```htdocs\Chat.php <?php use Ratchet\Server\IoServer; use Ratchet\Http\HttpServer; use Ratchet\WebSocket\WsServer; use htdocs\Chat; require_once 'C:\xampp\htdocs\vendor\autoload.php'; $server = IoServer::factory(new HttpServer(new WsServer(new Chat())), 8080); $server->run(); ```
AbeTakashi

2021/08/22 08:07

んー、XAMPPなんですね。Class not foundですからファイル名やネームスペース、クラス名がちゃんと合ってない(大文字・小文字の違いなど?)とかだと思いますが、XAMPPだとなにか特殊な事情があるかもしれません(私はXAMPPは使わないので具体的なアドバイスはできません)。とにかく、WebSocket connection・・・のエラーの原因は間違いなくこれだとは思います。
ryouya

2021/08/27 23:01

ご回答ありがとうございます! 連絡、たびたび遅れてしまい申し訳ございません。 承知しました。 スペルミス、環境の問題を踏まえて再度確認してみます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問