const fs = require("fs"); const http = require("http"); const WebSocket = require("ws");…
- User
const fs = require("fs"); const http = require("http"); const WebSocket = require("ws"); const path = require("path"); const url = require("url"); const uuid = require("uuid");
// 静态文件服务的目录 const staticBasePath = "./uploads"; let hostName = "";
const server = http.createServer((req, res) => { // 存储请求的 host 名称 hostName = req.headers.host; const parsedUrl = url.parse(req.url); const sanitizePath = path.normalize(parsedUrl.pathname).replace(/^(..[/\])+/, ""); let pathname = path.join(staticBasePath, sanitizePath);
codefs.exists(pathname, exist => { if (!exist) { res.statusCode = 404; res.end(`文件 ${pathname} 未找到!`); return; } // 如果找到文件则读取并返回 fs.readFile(pathname, (err, data) => { if (err) { res.statusCode = 500; res.end(`无法读取文件: ${err}.`); } else { // 修改Content-Type,根据不同文件类型返回相应地MIME类型 if (pathname.endsWith(".html")) { res.setHeader("Content-Type", "text/html"); } else if (pathname.endsWith(".css")) { res.setHeader("Content-Type", "text/css"); } else if (pathname.endsWith(".js")) { res.setHeader("Content-Type", "application/javascript"); } else if (pathname.endsWith(".jpg") || pathname.endsWith(".jpeg")) { res.setHeader("Content-Type", "image/jpeg"); } else if (pathname.endsWith(".png")) { res.setHeader("Content-Type", "image/png"); } res.end(data); } }); });});
const wss = new WebSocket.Server({ server });
wss.on("connection", ws => { ws.on("message", message => { const data = JSON.parse(message);
code - Assistant
- User
- Assistant
要编写一个Python的图形化客户端以与上述Node.js后端代码交互,我们可以使用
websocket-client库连接到WebSocket服务器,以及tkinter库来创建图形用户界面(GUI)。下面是一个简单的Python客户端示例代码:
python - User
Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\牛逼哥\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\牛逼哥\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "D:\ws\pythonProject\client.py", line 63, in start_websocket ws = websocket.WebSocketApp(SERVER, AttributeError: module 'websocket' has no attribute 'WebSocketApp'
- Assistant
这个异常表明
websocket模块中没有找到WebSocketApp这个属性。这通常出现在你可能没有安装正确的websocket-client包,或者你安装的是名为websocket的不同包,这导致了名称冲突。解决此问题,请确保安装正确的
websocket-client包,并且不存在名称冲突。以下是正确的安装和导入步骤:-
首先,确保你安装了
websocket-client。打开终端或命令提示符,运行以下命令来安装或更新到最新版本:shpip install -U websocket-client -
在你的Python代码中,确保正确导入了
websocket。你需要确保你的导入语句是import websocket而不是from websocket import *,因为import *可能不会导入所有你需要的属性。 -
还有一个常见的问题,就是创建了一个名为
websocket.py的文件在你的项目中,这将覆盖库的导入。确保你的任何Python文件都不要命名为websocket.py,同时检查是否有名为websocket.pyc的编译文件存在于你的项目文件夹里,如果有,也要删除掉。 -
最后,检查你的Python脚本文件所在的文件夹(或任何在Python路径中的文件夹)是否含有与
websocket-client库同名的文件或文件夹。这可能会导致Python导入错误的模块。
请根据以上步骤进行检查和调整,然后再次尝试运行你的客户端代码。
-