• websocket实现go(server)与c#(client)通讯


    go 服务端

    使用到github.com/gorilla/websocket

    package main
    
    import (
    	"fmt"
    	"github.com/gorilla/websocket"
    	"log"
    	"net/http"
    )
    
    func main() {
    	var upgrader = websocket.Upgrader{
    		ReadBufferSize:  1024,
    		WriteBufferSize: 1024,
    		CheckOrigin: func(r *http.Request) bool {
    			return true //允许跨域
    		},
    	}
    	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { //将所有的请求转换为websocket
    		upgrader.CheckOrigin = func(r *http.Request) bool {
    			return true
    		}
    		conn, err := upgrader.Upgrade(writer, request, nil)
    		if err != nil {
    			log.Fatal(err)
    		}
    		for {
    			t, msg, err := conn.ReadMessage()
    			if err != nil {
    				fmt.Printf("read error:%v\n", err)
    				break
    			}
    			fmt.Printf("[ws]recv count:%d recv:%s,msg type:%d\n", len(msg), string(msg), t)
    		}
    	})
    
    	err := http.ListenAndServe("127.0.0.1:8081", nil)
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    C#客户端

    C#操作websocket当客户端使用时使用System.Net.Websockets这个命名空间下的ClientWebSocket
    winform的设计界面如下:

    在这里插入图片描述
    代码如下:

    public partial class Form1 : Form
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            System.Net.WebSockets.ClientWebSocket client = new System.Net.WebSockets.ClientWebSocket();
            public Form1()
            {
                InitializeComponent();
                
            }
    
            private async void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    var content=this.rtbContent.Text;
                    if (string.IsNullOrEmpty(content))
                    {
                        MessageBox.Show("请输入内容来发送");
                        return;
                    }
                    if (client.State != System.Net.WebSockets.WebSocketState.Open)
                    {
                        tokenSource = new CancellationTokenSource();
                        client = new System.Net.WebSockets.ClientWebSocket();
                        //client.Options.KeepAliveInterval = TimeSpan.FromSeconds(1);
                        await client.ConnectAsync(new Uri("ws://127.0.0.1:8081"), tokenSource.Token);
                        var bytes = new byte[10240];
                        var array = new ArraySegment<byte>(bytes);
                        Task.Factory.StartNew(async () =>
                        {
                            while (true)
                            {
                                try
                                {
                                    var msg = await client.ReceiveAsync(array, tokenSource.Token);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message);
                                    tokenSource.Cancel();
                                    return;
                                }
                            }
                        });
                    }
                    var buffer = Encoding.UTF8.GetBytes(content);
                    await client.SendAsync(new ArraySegment<byte>(buffer), System.Net.WebSockets.WebSocketMessageType.Text, true, tokenSource.Token);
                    MessageBox.Show($"已发送{buffer.Length}个字节");
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.ToString());
                }
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    注意:无论是客户端断开还是服务端断开,如果正在读取消息,则会触发错误。利用此机制可以很方便的处理重连问题。

    在这里插入图片描述

  • 相关阅读:
    拼图小游戏Java简易版
    vue之axios的封装
    Spring Boot 启动流程
    CPVT:美团提出动态位置编码,让ViT的输入更灵活 | ICLR 2023
    计及调频成本和荷电状态恢复的多储能系统调频功率双层优化【蓄电池经济最优目标下充放电】(基于matlab+yalmip+cplex的蓄电池出力优化)
    JS 数据类型
    【Freeradius】使用Freeradius、LDAP和Google Authenticator实现双因素身份验证
    Python 列表操作指南1
    QCefView入门及环境配置
    Curve 文件存储的缓存策略
  • 原文地址:https://blog.csdn.net/lishuangquan1987/article/details/133583520