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

来源:互联网 发布:淘宝账号注销后会怎样 编辑:程序博客网 时间:2024/06/06 02:58

我本人也才接触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. }
原创粉丝点击