gpt4 book ai didi

gorilla Websocket 没有收到消息

转载 作者:IT王子 更新时间:2023-10-29 02:10:03 30 4
gpt4 key购买 nike

我正在 Golang 中构建一个与 Gorilla websockets 通信的网关。

我在 Ubuntu 16.04 上运行它,目前正在使用 .NET 控制台应用程序对其进行测试。

在 Windows 上使用 Wireshark 并在 Ubuntu 上使用 sniffit 已确定消息从 Windows 客户端正确发送并由 Ubuntu box 接收

然而,在我的代码中,有时在一些成功的消息之后,有时在没有成功之后,我的网关无法读取消息(仍然坐在 _, msg, errCon := conn.ReadMessage())

输出示例如下:

2018/03/27 02:38:06 Awaiting Message ... 2018/03/27 02:38:07 Message received: main.AdminRequest{Data:"{\"SomeDataHeader\":\"SomeData\"}", Requestor:"user", Type:"JustDoSomethingRequest", Ukey:"talca"} 2018/03/27 02:38:07 {"SomeDataHeader":"SomeData"} 2018/03/27 02:38:07 Awaiting Message ...

正如我之前所说,它可能会收到一些这样的消息,但是,尽管两端的网络流量仍在继续,但不会收到更多消息

我对 Golang 还很陌生,并且在假设我遗漏了一些东西的情况下工作。

为了简洁起见,我在下面的代码中删除了错误处理等,但这是失败代码的示例。

编辑 根据要求,我在下面添加了 Golang 完整代码和 C# 客户端代码(尽管,正如我所说,Wireshark 和 sniffit 已确定数据正在通过网络传输)

package main

import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
"encoding/json"
"log"
)

var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}

type AdminRequest struct {
Data string `json:"Data"`
Requestor string `json:"Requestor"`
Type string `json:"Type"`
Ukey string `json:"Ukey"`
}

func main() {

http.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) {
var conn, _ = upgrader.Upgrade(w, r, nil)

go func(conn *websocket.Conn) {
for {
_, _, err := conn.ReadMessage()
if err != nil {
log.Println("Close: "+ err.Error())
conn.Close()
return
}
}
}(conn)


go func(conn *websocket.Conn) {
for {

log.Println("Awaiting Message ...")
_, msg, errCon := conn.ReadMessage()

if errCon != nil {
log.Println("Read Error:", errCon)
break
}

log.Println("Message received: ")

var r AdminRequest

if err := json.Unmarshal(msg, &r); err != nil {

log.Println("Error: " + err.Error());
return;
}

fmt.Printf("%#v\n", r)
log.Println(r.Data);
}
}(conn)

})

http.ListenAndServe(":3000", nil)
}

C#代码:

public class Client : IDisposable
{
private ClientWebSocket _socket;


string _address;
int _port;
public Client(string address)
{
_address = address;

_socket = new ClientWebSocket();
}

public async void SetupForReceivingStuffs()
{
while (_socket.State == WebSocketState.Open)
{
ArraySegment<byte> receivedBytes = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult result = await _socket.ReceiveAsync(receivedBytes, CancellationToken.None);

Console.WriteLine(Encoding.UTF8.GetString(receivedBytes.Array, 0, result.Count));
}
}

public async void SetupForSendingStuffs(ConcurrentQueue<AdminRequest> queue)
{
while (_socket.State == WebSocketState.Open)
{
AdminRequest next;

while (queue.Count > 0)
{
if (queue.TryDequeue(out next))
{
await Send(next);
}
}

await Task.Yield();
}
}

public async Task Connect()
{
while (_socket.State != WebSocketState.Open)
{
try
{
_socket = new ClientWebSocket();
await _socket.ConnectAsync(new Uri(_address), CancellationToken.None);

Console.WriteLine("Socket state: " + _socket.State);
}
catch (Exception ex)
{
//Not getting hit
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
}



public Task Send<TData>(TData data)
{
string text = JsonConvert.SerializeObject(data);

var encoded = Encoding.UTF8.GetBytes(text);
var buffer = new ArraySegment<Byte>(encoded, 0, encoded.Length);

return _socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
}


public void Dispose()
{
_socket.Dispose();
}
}

调用者:

class Program
{
static ConcurrentQueue<AdminRequest> _toSend;

static void Main(string[] args)
{
_toSend = new ConcurrentQueue<AdminRequest>();

Client client = new Client("ws:/(myip):(myport)/a");
client.Connect().Wait();

//client.SetupForReceivingStuffs();
client.SetupForSendingStuffs(_toSend);

WriteInstructions();

LoopAuto();

Console.WriteLine("Bye");
}

private static void LoopAuto()
{
DateTime nextMessage = DateTime.Now;

while (true)
{

if (DateTime.Now < nextMessage) continue;
Console.WriteLine("Next");
nextMessage = DateTime.Now.AddSeconds(2);

_toSend.Enqueue(new AdminRequest
{
Data = "{\"SomeDataHeader\":\"SomeData\"}",
Requestor = "user",
Type = "JustDoSomethingRequest",
Ukey = "talca"
});
}
}

private static ConsoleKeyInfo LoopManual()
{
ConsoleKeyInfo info;
do
{
info = Console.ReadKey(true);

if (info.KeyChar == '1')
{
_toSend.Enqueue(new AdminRequest
{
Data = "{\"SomeDataHeader\":\"SomeData\"}",
Requestor = "user",
Type = "JustDoSomethingRequest",
Ukey = "talca"
});
}
else if (info.KeyChar == 'i')
{
WriteInstructions();
}

} while (info.KeyChar != 'x');

return info;
}

private static void WriteInstructions()
{
Console.WriteLine("1. Send New Message");
Console.WriteLine("i. Instructions (these lines)");
Console.WriteLine("x: Exit");
}
}

最佳答案

应用程序运行两个 goroutine,它们循环读取消息。第一个对收到的消息不做任何事情。第二个解析并记录消息。您看不到任何输出,因为第一个 goroutine 正在接收消息。

第一个 goroutine 似乎没有任何作用。删除第一个 goroutine 以解决问题。

删除第一个 goroutine 也解决了数据竞争问题。 Concurrent reads on a websocket connection are not supported . race detector将报告此问题。

这是包含其他修复和改进的更新代码。网络/http 服务器将处理程序称为每个连接的 goroutine。使用 tha goroutine 而不是启动另一个 goroutine。使用 websocket 包的 JSON 辅助方法。

package main

import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
"encoding/json"
"log"
)

var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}

type AdminRequest struct {
Data string `json:"Data"`
Requestor string `json:"Requestor"`
Type string `json:"Type"`
Ukey string `json:"Ukey"`
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
for {
var r AdminRequest
if err := conn.ReadJSON(&r); err != nil {
log.Println(err)
break
}
fmt.Printf("%#v\n", r)
log.Println(r.Data);
}
}

func main() {
http.HandleFunc("/a", wsHandler)
http.ListenAndServe(":3000", nil)
}

关于 gorilla Websocket 没有收到消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49504016/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com