Google GO与C#之间的TCP通信案例

简介:

我本人也才接触GO两个多月的历史,看了几本英文教程,读了些Github上面的源码,但已经被GO的语言的简洁和强大的并发能力所吸收,也打算继续深入的学习,并应用到自己的工作之中。GO语言目前主要适用于服务端的开发,我参考了一些网络上的教程,做了一些TCP服务端的小练习,其中服务端用GO语言开发,客户端采用C#。具体参考如下的代码:https://github.com/yfl8910/gotcpserver

效果图如下:

服务端代码:

 
  1. package main
  2. import (
  3. "net"
  4. "fmt"
  5. )
  6. var ( maxRead = 25
  7. msgStop = []byte("cmdStop")
  8. msgStart = []byte("cmdContinue")
  9. )
  10. func main() {
  11. hostAndPort := "localhost:54321"
  12. listener := initServer(hostAndPort)
  13. for {
  14. conn, err := listener.Accept()
  15. checkError(err, "Accept: ")
  16. go connectionHandler(conn)
  17. }
  18. }
  19. func initServer(hostAndPort string) *net.TCPListener {
  20. serverAddr, err := net.ResolveTCPAddr("tcp", hostAndPort)
  21. checkError(err, "Resolving address:port failed: '" + hostAndPort + "'")
  22. //listener, err := net.ListenTCP("tcp", serverAddr)
  23. listener, err := net.ListenTCP("tcp", serverAddr)
  24. checkError(err, "ListenTCP: ")
  25. println("Listening to: ", listener.Addr().String())
  26. return listener
  27. }
  28. func connectionHandler(conn net.Conn) {
  29. connFrom := conn.RemoteAddr().String()
  30. println("Connection from: ", connFrom)
  31. talktoclients(conn)
  32. for {
  33. var ibuf []byte = make([]byte, maxRead + 1)
  34. length, err := conn.Read(ibuf[0:maxRead])
  35. ibuf[maxRead] = 0 // to prevent overflow
  36. switch err {
  37. case nil:
  38. handleMsg(length, err, ibuf)
  39. default:
  40. goto DISCONNECT
  41. }
  42. }
  43. DISCONNECT:
  44. err := conn.Close()
  45. println("Closed connection:" , connFrom)
  46. checkError(err, "Close:" )
  47. }
  48. func talktoclients(to net.Conn) {
  49. wrote, err := to.Write(msgStart)
  50. checkError(err, "Write: wrote " + string(wrote) + " bytes.")
  51. }
  52. func handleMsg(length int, err error, msg []byte) {
  53. if length > 0 {
  54. for i := 0; ; i++ {
  55. if msg[i] == 0 {
  56. break
  57. }
  58. }
  59. fmt.Printf("Received data: %v", string(msg[0:length]))
  60. fmt.Println(" length:",length)
  61. }
  62. }
  63. func checkError(error error, info string) {
  64. if error != nil {
  65. panic("ERROR: " + info + " " + error.Error()) // terminate program
  66. }
  67. }

客户端代码:

 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Threading;
  11. namespace TcpClient
  12. {
  13. public partial class Form1 : Form
  14. {
  15. private IPAddress _ipServer; //服务器IP
  16. private IPEndPoint _myServer; //服务器终端
  17. private Socket _connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//连接套接字
  18. private int _port; //端口
  19. private Thread receiveThread = null;
  20. public Form1()
  21. {
  22. InitializeComponent();
  23. }
  24. private bool ValidateInfo() //检验所填信息是否合法
  25. {
  26. if (!IPAddress.TryParse(txtbxIP.Text, out _ipServer))
  27. {
  28. MessageBox.Show("IP地址不合法!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  29. return false;
  30. }
  31. if (!int.TryParse(txtbxPortNum.Text, out _port))
  32. {
  33. MessageBox.Show("端口号不合法!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  34. return false;
  35. }
  36. else
  37. {
  38. if (_port < 1024 || _port > 65535)
  39. {
  40. MessageBox.Show("端口号不合法!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  41. return false;
  42. }
  43. }
  44. return true;
  45. }
  46. private bool ConnectServer() //连接服务器
  47. {
  48. try
  49. {
  50. _connectSocket.Connect(_myServer);
  51. _connectSocket.Send(System.Text.Encoding.UTF8.GetBytes(txtbxUser.Text.ToString()));
  52. return true;
  53. }
  54. catch
  55. {
  56. MessageBox.Show("服务器连接异常", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  57. return false;
  58. }
  59. }
  60. private void button1_Click(object sender, EventArgs e)
  61. {
  62. try
  63. {
  64. _connectSocket.Send(System.Text.Encoding.UTF8.GetBytes(comboBox1.Text.ToString()));
  65. }
  66. catch
  67. {
  68. MessageBox.Show("服务器连接异常", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  69. }
  70. }
  71. private void button3_Click(object sender, EventArgs e)
  72. {
  73. if (!ValidateInfo())
  74. {
  75. return;
  76. }
  77. _myServer = new IPEndPoint(_ipServer, _port);
  78. if (ConnectServer() == true)
  79. {
  80. MessageBox.Show("连接成功!");
  81. }
  82. }
  83. private void button2_Click(object sender, EventArgs e)
  84. {
  85. this.Close();
  86. }
  87. private void button4_Click(object sender, EventArgs e)
  88. {
  89. for (int i = 0; i < 1000; i++) {
  90. Socket _connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  91. _connectSocket.Connect(_myServer);
  92. _connectSocket.Send(System.Text.Encoding.UTF8.GetBytes(comboBox1.Text.ToString()+i));
  93. Thread.Sleep(2);
  94. }
  95. }
  96. }
  97. }
目录
相关文章
|
1月前
|
数据处理 C# C++
如何使用C#和C++结构体实现Socket通信
如何使用C#和C++结构体实现Socket通信
|
1月前
|
存储 消息中间件 大数据
Go语言在大数据处理中的实际应用与案例分析
【2月更文挑战第22天】本文深入探讨了Go语言在大数据处理中的实际应用,通过案例分析展示了Go语言在处理大数据时的优势和实践效果。文章首先介绍了大数据处理的挑战与需求,然后详细分析了Go语言在大数据处理中的适用性和核心技术,最后通过具体案例展示了Go语言在大数据处理中的实际应用。
|
1月前
|
负载均衡 算法 数据库连接
Go语言性能优化实践:案例分析与解决方案
【2月更文挑战第18天】本文将通过具体的案例分析,探讨Go语言性能优化的实践方法和解决方案。我们将分析几个典型的性能瓶颈问题,并详细介绍如何通过优化代码、调整并发模型、改进内存管理等方式来提升程序的性能。通过本文的学习,读者将能够掌握一些实用的Go语言性能优化技巧,为实际项目开发中的性能优化工作提供指导。
|
3月前
|
安全 Go 数据处理
Go语言CSP编程实战:通道通信技术
Go语言CSP编程实战:通道通信技术
43 0
|
3月前
|
安全 Go
Go新手步步为赢:并发编程通信指南
Go新手步步为赢:并发编程通信指南
25 0
|
1月前
|
存储 C#
C#中的序列化和反序列化案例
C#中的序列化和反序列化案例
12 0
|
1月前
|
Kubernetes Go 开发者
Go语言与Docker容器结合的实践应用与案例分析
【2月更文挑战第23天】本文通过分析实际案例,探讨了Go语言与Docker容器技术结合的实践应用。通过详细阐述Go语言在容器化环境中的开发优势,以及Docker容器技术在Go应用部署中的重要作用,本文旨在为读者提供Go语言与Docker容器结合的具体实现方法和实际应用场景。
|
1月前
|
SQL 机器学习/深度学习 缓存
Go语言Web应用实战与案例分析
【2月更文挑战第21天】本文将通过实战案例的方式,深入探讨Go语言在Web应用开发中的应用。我们将分析一个实际项目的开发过程,展示Go语言在构建高性能、可扩展Web应用方面的优势,并分享在开发过程中遇到的问题和解决方案,为读者提供宝贵的实战经验。
|
1月前
|
设计模式 Java Go
Go语言高级面向对象编程技巧与实战案例
【2月更文挑战第10天】本文将深入探讨Go语言中的高级面向对象编程技巧,并通过实战案例展示如何应用这些技巧解决实际问题。我们将了解如何使用设计模式、测试与调试面向对象程序、性能优化与内存管理等高级话题,以提升Go语言编程的水平和代码质量。
|
2月前
|
Go 调度 开发者
Go语言并发基础:轻量级线程与通道通信
【2月更文挑战第6天】本文介绍了Go语言在并发编程方面的基础知识和核心概念。我们将深入探讨goroutine(轻量级线程)的创建与调度,以及如何利用channel进行goroutine间的通信与同步。此外,还将简要提及select语句的使用,并解释其在处理多个channel操作时的优势。