從go程式中發訊息給winform(C#)
阿新 • • 發佈:2021-11-03
背景:服務端語言為GO,客戶端語言為:C#(WinForm);在客戶端操作後,伺服器會產生一些訊息,需要將這些訊息實時的傳遞給客戶端。
一、C#核心程式碼
using Hprose.RPC; using Hprose.RPC.Plugins.Log; using Hprose.RPC.Plugins.Push; using System; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using System.Windows.Forms; namespace win_push_msg_client { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void 測試ToolStripMenuItem_Click(object sender, EventArgs e) { callAppendLog("開始"); Task.Factory.StartNew(() => { try { #region // 服務端啟動 string addrStr = "127.0.0.1"; IPAddress iPAddress = Dns.GetHostAddresses(addrStr)[0]; TcpListener server = new TcpListener(iPAddress, 8899); server.Start(); var service = new Broker(new Service()).Service; ServiceCodec.Instance.Debug = true; service.Use(Log.IOHandler) .Use(Log.InvokeHandler) .Bind(server); // 啟動訂閱服務 var client = new Client(string.Format("tcp4://{0}:8899", addrStr)); var prosumer = new Prosumer(client, "C#"); prosumer.OnSubscribe += (topic) => { this.callAppendLog(topic + " 訂閱成功."); }; prosumer.OnUnsubscribe += (topic) => { this.callAppendLog(topic + " 取消訂閱成功"); }; prosumer.Subscribe<string>("log_msg", (data) => { this.callAppendLog(data); }); this.callAppendLog("已訂閱主題:log_msg"); #endregion } catch (Exception ex) { this.callAppendLog(ex.Message); } }); } private void callAppendLog(string msg) { this.Invoke(new Action(() => { this.richTextBox1.AppendText(msg); this.richTextBox1.AppendText("\n"); })); } } }
二、GO核心程式碼:
package main import ( "github.com/hprose/hprose-golang/v3/rpc" "github.com/hprose/hprose-golang/v3/rpc/plugins/push" "time" ) func main() { client2 := rpc.NewClient("tcp4://127.0.0.1:8899/") prosumer2 := push.NewProsumer(client2, "傳送方1") time.Sleep(time.Millisecond * 100) prosumer2.Push(View Code"人來了1a", "log_msg", "C#") prosumer2.Push("人來了2c", "log_msg", "C#") }
本文來自部落格園,作者:xiaoyongdata(微訊號:xiaoyongdata),轉載請註明原文連結:https://www.cnblogs.com/xiaoyongdata/p/15505821.html