Vscode语言客户端扩展-如何从服务器向客户端发送消息?

10
我一直在开发一个使用语言服务器协议的vscode扩展,包括客户端和服务器。
目前,我正在尝试做以下事情:当服务器检测到特定条件时,请求客户端将一定数量的文件加载到工作区中。
我在做这件事情时遇到了严重的问题。由于语言服务器协议没有特定的请求来执行此操作,所以我考虑从服务器向客户端发送消息,一旦客户端检测到此消息,它就会执行此命令。
问题是,我也不知道该如何做到这一点。请问有人能帮助我吗?
2个回答

22
只要您确定名称不会与现有的LSP方法冲突,就可以定义自己的任意方法。例如,在official lsp-sample中,您可以这样做:
(在client/src/extension.ts的末尾)
let client = new LanguageClient('lspSample', 'Language Server Example', serverOptions, clientOptions);
client.onReady().then(() => {
    client.onNotification("custom/loadFiles", (files: Array<String>) => {
        console.log("loading files " + files);
    });
});
context.subscriptions.push(client.start());

(在server/src/server.tsdocuments.onDidChangeContent监听器中)
var files = ["path/to/file/a.txt", "path/to/file/b.txt"];
connection.sendNotification("custom/loadFiles", [files]);

每当更改.txt文件的内容时(因为示例使用plaintext作为其文档选择器),将以下内容输出到开发控制台:

loading files path/to/file/a.txt,path/to/file/b.txt

在自定义方法的名称、参数及调用方面,您几乎具有完全的灵活性。对于语言服务器来说,使用此类不属于协议的自定义方法以实现各种目的(高级功能、内部调试/开发功能等)非常普遍。

-1

2023年更新

现在(使用LSP版本8.1.0),您可以在官方的lsp-sample第51行上使用以下代码片段来修改client/src/extension.ts文件:


    const loadFilesListener = client.onNotification('custom/loadFiles', (files: string[]) => {
        console.log('loading files ' + files);
    })
    context.subscriptions.push(saveDocumentNotificationListener)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接