websocket致命错误消息:“无法监听tcp://0.0.0.0:8080:地址已在使用中”

-3 投票
0 回答
36 浏览
提问于 2025-04-12 08:00

我在尝试为我的网站创建一个websocket服务器时,遇到了一个致命错误,提示“无法在tcp://0.0.0.0:8080上监听:地址已在使用中”。我该如何解决这个问题呢?

问题是,我想在我的网站上设置一个websocket服务器,但收到了以下错误信息:“致命错误:未捕获的运行时异常:无法在“tcp://0.0.0.0:8080”上监听:地址已在使用中。”这个错误发生在TcpServer.php文件的第184行。我该如何排查和修复这个问题,以便成功在我的网站上设置websocket服务器呢?

我想实现管理员的Python程序和Python客户端之间通过PHP服务器实时发送数据。

这是管理员的Python脚本(发送方)

import asyncio
import websockets
import json

async def send_array():
    uri = "ws://example.com:8080"
    async with websockets.connect(uri, timeout=60.0) as websocket:
        array_data = [1, 2, 3, "hello"]
        await websocket.send(json.dumps(array_data))

asyncio.run(send_array())

当我运行它时出现的错误是

引发超时错误

这是PHP文件服务器

require_once 'vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class WebSocketServer implements MessageComponentInterface {
    protected $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->clients->attach($conn);
        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        $data = json_decode($msg, true);

        if (is_array($data)) {
            // Process the array data as needed
            echo "Received array data: " . print_r($data, true) . "\n";

            // Send the array data to all connected clients
            foreach ($this->clients as $client) {
                if ($from !== $client) {
                    $client->send(json_encode($data));
                }
            }
        }
    }

    public function onClose(ConnectionInterface $conn) {
        $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();
    }
}

PHP文件的错误是

致命错误信息,提示“无法在tcp://0.0.0.0:8080上监听:地址已在使用中”

这是Python客户端(接收方)

import asyncio
import json
import websockets

# Replace this URL with the URL of your PHP server
url = "ws://example:8080"

async def receive_array():
    async with websockets.connect(url) as websocket:
        while True:
            # Receive data from the server
            data = await websocket.recv()
            array_data = json.loads(data)

            # Print the received data for demonstration purposes
            print("Received data: ", array_data)

# Run the real-time client
asyncio.get_event_loop().run_until_complete(receive_array())
asyncio.get_event_loop().run_forever()

我希望能得到一些指导,帮助我排查和解决在我的网站上设置websocket服务器时出现的“无法在tcp://0.0.0.0:8080上监听:地址已在使用中”的错误。我想实现管理员的Python程序和Python客户端之间通过PHP服务器实时发送数据。

0 个回答

暂无回答

撰写回答