搜索
首页后端开发GolangGolang jsonrpc2 服务器在哪里监听?

Golang jsonrpc2 服务器在哪里监听?

Feb 08, 2024 pm 09:27 PM
golang开发overflowlsp

Golang jsonrpc2 服务器在哪里监听?

Golang jsonrpc2 服务器在哪里监听?这是许多Golang开发者在使用jsonrpc2协议时经常遇到的问题。在Golang中,jsonrpc2服务器监听的位置取决于代码的实现方式。一种常见的做法是将服务器监听在特定的端口上,以便接收来自客户端的请求。另外,也可以将服务器监听在特定的网络接口上,例如本地回环接口(localhost)或指定的IP地址上。为了确保服务器能够正常监听请求并进行处理,开发者需要在代码中明确指定监听的位置。

问题内容

我想在golang中创建一个简单的lsp服务器,到目前为止这是我编写的代码:

package main

import (
    "context"
    "fmt"
    "os"
    "sync"

    "github.com/sourcegraph/jsonrpc2"
)

type lspserver struct {
    // the symmetric connection
    conn jsonrpc2.conn

    // check if the connection is available
    connmutex sync.mutex

    // shutdown
    shutdown bool
}

func newlspserver() *lspserver {
    return &lspserver{}
}

func (s *lspserver) initialize(ctx context.context) error {
    // to implement
    return nil
}

func (s *lspserver) handle(context.context, *jsonrpc2.conn, *jsonrpc2.request) (result interface{}, err error) {
    fmt.println("handling request...")
    // to implement
    return nil, nil
}

func (s *lspserver) serve(ctx context.context) {
    fmt.println("starting lsp server...")
    // what port is this server listening on?
    // it is listening on port 4389

    // create a new jsonrpc2 stream server
    handler := jsonrpc2.handlerwitherror(s.handle)

    // create a new jsonrpc2 stream server
    <-jsonrpc2.newconn(
        context.background(),
        jsonrpc2.newbufferedstream(os.stdin, jsonrpc2.vscodeobjectcodec{}),
        handler).disconnectnotify()
}

func main() {

    // create a new lsp server
    server := newlspserver()
    server.serve(context.background())

}

它可以运行,但我不知道它在哪个端口上运行,或者一般如何通过客户端调用它。有人有什么想法吗?

我认为应该是端口4389,但不是那个

我正在使用此脚本进行测试:

import json
import requests

def rpc_call(url, method, args):
    headers = {'content-type': 'application/json'}
    payload = {
        "method": method,
        "params": [args],
        "jsonrpc": "2.0",
        "id": 1,
    }
    response = requests.post(url, data=json.dumps(payload), headers=headers).json()
    return response['result']

url = 'http://localhost:4389/'

emailArgs = {'To': '[email&#160;protected]','Subject': 'Hello', 'Content': 'Hi!!!'}
smsArgs = {'Number': '381641234567', 'Content': 'Sms!!!'}
print(rpc_call(url, 'email.SendEmail', emailArgs))
print(rpc_call(url, 'sms.SendSMS', smsArgs))

我认为这是正确的,因为我从另一个 stackoverflow 问题中获取了这个客户

解决方法

我明白了:

handlerwitherror(s.handle)

    // create a new jsonrpc2 stream server
    <-jsonrpc2.newconn(
        context.background(),
        jsonrpc2.newbufferedstream(os.stdin, jsonrpc2.vscodeobjectcodec{}),
        handler).disconnectnotify()
}

这意味着您的代码通过标准输入和输出(stdin/stdout)使用 json-rpc,而不是通过网络连接。
当您使用 os.stdin 作为 jsonrpc2.newbufferedstream 的参数时,您指定输入应来自运行服务器的进程的标准输入。并且响应将被发送到标准输出。

因此,服务器没有侦听任何网络端口。它与直接发送到其标准输入和输出的数据进行交互。这通常用于进程间通信,例如,当您希望一个进程调用服务器进程并接收响应时。
例如,请参阅“go:与另一个进程进行双向通信?”或davidelorenzoli/stdin-stdout-ipc

如果您希望 json-rpc 服务器侦听网络端口,则需要使用 net。您还需要修改客户端脚本以将其请求发送到正确的网络端口,而不是向 url 发送 http 请求。

package main

import (
    "context"
    "net"
    "log"
    "sync"

    "github.com/sourcegraph/jsonrpc2"
)

type LSPServer struct {
    // The symmetric connection
    conn jsonrpc2.Conn

    // Check if the connection is available
    connMutex sync.Mutex

    // shutdown
    shutdown bool
}

func NewLSPServer() *LSPServer {
    return &LSPServer{}
}

func (s *LSPServer) Initialize(ctx context.Context) error {
    // Initialize here if needed
    return nil
}

func (s *LSPServer) Handle(context.Context, *jsonrpc2.Conn, *jsonrpc2.Request) (result interface{}, err error) {
    fmt.Println("Handling request...")
    // Handle something
    return nil, nil
}

func (s *LSPServer) Serve(ctx context.Context) {
    fmt.Println("Starting LSP server...")
    
    // Listen on TCP port 4389 on all available unicast and
    // anycast IP addresses of the local system.
    l, err := net.Listen("tcp", "localhost:4389")
    if err != nil {
        log.Fatal(err)
    }
    defer l.Close()

    for {
        // Wait for a connection.
        conn, err := l.Accept()
        if err != nil {
            log.Fatal(err)
        }

        // Handle the connection in a new goroutine.
        go func(c net.Conn) {
            // Create a new jsonrpc2 stream server
            handler := jsonrpc2.HandlerWithError(s.Handle)
            <-jsonrpc2.NewConn(
                ctx,
                jsonrpc2.NewBufferedStream(c, jsonrpc2.VSCodeObjectCodec{}),
                handler).DisconnectNotify()
            c.Close()
        }(conn)
    }
}

func main() {
    // Create a new LSP server
    server := NewLSPServer()
    go server.Serve(context.Background()) // run Serve in a separate goroutine
    select {} // wait forever
}

这是一个基本示例,其中 serve 方法创建一个 tcp 侦听器,侦听本地主机的端口 4389。然后它进入一个等待连接的循环,当它获得连接时,它会启动一个新的 goroutine 来使用 json-rpc 服务器处理该连接。

在客户端,您需要打开到服务器的 tcp 连接,将 json-rpc 请求写入该连接,然后读取响应。

您不能像在 python 脚本中那样使用 requests,因为它用于 http 请求,不是原始 tcp 连接。
您将需要在 python 中使用 socket,或在您客户端的语言,以创建 tcp 连接并通过它发送/接收数据。

但请记住,lsp(语言服务器协议) 通过 stdin/stdout 运行而不是网络套接字。
这是因为 lsp 服务器通常由编辑器/ide 作为子进程启动,并通过这些通道直接通信。因此,根据您的用例,原始的 stdin/stdout 方法可能更合适。

以上是Golang jsonrpc2 服务器在哪里监听?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
如何使用'字符串”软件包逐步操纵字符串如何使用'字符串”软件包逐步操纵字符串May 13, 2025 am 12:12 AM

Go的strings包提供了多种字符串操作功能。1)使用strings.Contains检查子字符串。2)用strings.Split将字符串分割成子字符串切片。3)通过strings.Join合并字符串。4)用strings.TrimSpace或strings.Trim去除字符串首尾的空白或指定字符。5)用strings.ReplaceAll替换所有指定子字符串。6)使用strings.HasPrefix或strings.HasSuffix检查字符串的前缀或后缀。

Go Strings软件包:如何改进我的代码?Go Strings软件包:如何改进我的代码?May 13, 2025 am 12:10 AM

使用Go语言的strings包可以提升代码质量。1)使用strings.Join()优雅地连接字符串数组,避免性能开销。2)结合strings.Split()和strings.Contains()处理文本,注意大小写敏感问题。3)避免滥用strings.Replace(),考虑使用正则表达式进行大量替换。4)使用strings.Builder提高频繁拼接字符串的性能。

GO BYTES软件包中最有用的功能是什么?GO BYTES软件包中最有用的功能是什么?May 13, 2025 am 12:09 AM

Go的bytes包提供了多种实用的函数来处理字节切片。1.bytes.Contains用于检查字节切片是否包含特定序列。2.bytes.Split用于将字节切片分割成smallerpieces。3.bytes.Join用于将多个字节切片连接成一个。4.bytes.TrimSpace用于去除字节切片的前后空白。5.bytes.Equal用于比较两个字节切片是否相等。6.bytes.Index用于查找子切片在largerslice中的起始索引。

使用GO的'编码/二进制”软件包掌握二进制数据处理:综合指南使用GO的'编码/二进制”软件包掌握二进制数据处理:综合指南May 13, 2025 am 12:07 AM

theEncoding/binarypackageingoisesenebecapeitProvidesAstandArdArdArdArdArdArdArdArdAndWriteBinaryData,确保Cross-cross-platformCompatibilitiational and handhandlingdifferentendenness.itoffersfunctionslikeread,写下,写,dearte,readuvarint,andwriteuvarint,andWriteuvarIntforPreciseControloverBinary

转到'字节”软件包快速参考转到'字节”软件包快速参考May 13, 2025 am 12:03 AM

回顾bytespackageingoiscialforhandlingbyteslicesandbuffers,offeringToolsforefficeMemoryManagement和datamAnipulation.1)ItProvidesfunctionalitiesLikeCreatingBuffers,比较,搜索/更换/更换/更换forlargedAtatAsetsets.n

掌握GO弦:深入研究'字符串”包装掌握GO弦:深入研究'字符串”包装May 12, 2025 am 12:05 AM

你应该关心Go语言中的"strings"包,因为它提供了处理文本数据的工具,从基本的字符串拼接到高级的正则表达式匹配。1)"strings"包提供了高效的字符串操作,如Join函数用于拼接字符串,避免性能问题。2)它包含高级功能,如ContainsAny函数,用于检查字符串是否包含特定字符集。3)Replace函数用于替换字符串中的子串,需注意替换顺序和大小写敏感性。4)Split函数可以根据分隔符拆分字符串,常用于正则表达式处理。5)使用时需考虑性能,如

GO中的'编码/二进制”软件包:您的二进制操作首选GO中的'编码/二进制”软件包:您的二进制操作首选May 12, 2025 am 12:03 AM

“编码/二进制”软件包interingoisentialForHandlingBinaryData,oferingToolSforreDingingAndWritingBinaryDataEfficely.1)Itsupportsbothlittle-endianandBig-endianBig-endianbyteorders,CompialforOss-System-System-System-compatibility.2)

Go Byte Slice操纵教程:掌握'字节”软件包Go Byte Slice操纵教程:掌握'字节”软件包May 12, 2025 am 12:02 AM

掌握Go语言中的bytes包有助于提高代码的效率和优雅性。1)bytes包对于解析二进制数据、处理网络协议和内存管理至关重要。2)使用bytes.Buffer可以逐步构建字节切片。3)bytes包提供了搜索、替换和分割字节切片的功能。4)bytes.Reader类型适用于从字节切片读取数据,特别是在I/O操作中。5)bytes包与Go的垃圾回收器协同工作,提高了大数据处理的效率。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器