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

开发 开发工具
Go语言是Google推出的一种全新的编程语言,具有简洁的设计、强大的并发能力以及美好的编程体验。

 我本人也才接触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.  
  12.     hostAndPort := "localhost:54321" 
  13.     listener := initServer(hostAndPort) 
  14.     for { 
  15.         conn, err := listener.Accept() 
  16.         checkError(err, "Accept: "
  17.         go connectionHandler(conn) 
  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. func connectionHandler(conn net.Conn) { 
  28.     connFrom := conn.RemoteAddr().String() 
  29.     println("Connection from: ", connFrom) 
  30.     talktoclients(conn) 
  31.     for { 
  32.         var ibuf []byte = make([]byte, maxRead + 1) 
  33.         length, err := conn.Read(ibuf[0:maxRead]) 
  34.         ibuf[maxRead] = 0 // to prevent overflow 
  35.     switch err { 
  36.     case nil: 
  37.         handleMsg(length, err, ibuf) 
  38.  
  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. func handleMsg(length int, err error, msg []byte) { 
  52.     if length > 0 { 
  53.         for i := 0; ; i++ { 
  54.             if msg[i] == 0 { 
  55.                 break 
  56.             } 
  57.         } 
  58.         fmt.Printf("Received data: %v"string(msg[0:length])) 
  59.         fmt.Println("   length:",length) 
  60.     } 
  61. func checkError(error error, info string) { 
  62.     if error != nil { 
  63. panic("ERROR: " + info + " " + error.Error()) // terminate program 

客户端代码:

  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.  
  12. namespace TcpClient 
  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.  
  25.         private bool ValidateInfo() //检验所填信息是否合法 
  26.         { 
  27.             if (!IPAddress.TryParse(txtbxIP.Text, out _ipServer)) 
  28.             { 
  29.                 MessageBox.Show("IP地址不合法!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 
  30.                 return false
  31.             } 
  32.            if (!int.TryParse(txtbxPortNum.Text, out _port)) 
  33.             { 
  34.                 MessageBox.Show("端口号不合法!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 
  35.                 return false
  36.             } 
  37.             else 
  38.             { 
  39.                 if (_port < 1024 || _port > 65535) 
  40.                 { 
  41.                     MessageBox.Show("端口号不合法!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 
  42.                     return false
  43.                 } 
  44.             } 
  45.             return true
  46.         } 
  47.  
  48.  
  49.         private bool ConnectServer() //连接服务器 
  50.         {           
  51.            try 
  52.             { 
  53.                 _connectSocket.Connect(_myServer); 
  54.                 _connectSocket.Send(System.Text.Encoding.UTF8.GetBytes(txtbxUser.Text.ToString())); 
  55.                 
  56.                 return true
  57.             } 
  58.             catch 
  59.             { 
  60.                 MessageBox.Show("服务器连接异常""错误", MessageBoxButtons.OK, MessageBoxIcon.Error); 
  61.                 return false
  62.             } 
  63.         } 
  64.  
  65.  
  66.         private void button1_Click(object sender, EventArgs e) 
  67.         { 
  68.             try 
  69.             {          
  70.                 _connectSocket.Send(System.Text.Encoding.UTF8.GetBytes(comboBox1.Text.ToString()));  
  71.             } 
  72.             catch 
  73.             { 
  74.                 MessageBox.Show("服务器连接异常""错误", MessageBoxButtons.OK, MessageBoxIcon.Error);    
  75.             } 
  76.             
  77.         } 
  78.  
  79.         private void button3_Click(object sender, EventArgs e) 
  80.         { 
  81.           
  82.             if (!ValidateInfo()) 
  83.             { 
  84.                 return
  85.             } 
  86.             _myServer = new IPEndPoint(_ipServer, _port); 
  87.  
  88.             if (ConnectServer() == true
  89.             { 
  90.                 MessageBox.Show("连接成功!"); 
  91.  
  92.             } 
  93.         } 
  94.         private void button2_Click(object sender, EventArgs e) 
  95.         { 
  96.             this.Close(); 
  97.         } 
  98.  
  99.         private void button4_Click(object sender, EventArgs e) 
  100.         { 
  101.             for (int i = 0; i < 1000; i++) { 
  102.                 Socket _connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
  103.                 _connectSocket.Connect(_myServer); 
  104.                 _connectSocket.Send(System.Text.Encoding.UTF8.GetBytes(comboBox1.Text.ToString()+i)); 
  105.                 Thread.Sleep(2); 
  106.              
  107.             } 
  108.             
  109.             
  110.         }    
  111.  
  112.     } 

原文链接:http://www.cnblogs.com/yfl8910/archive/2012/12/20/2825528.html

 

【编辑推荐】

 

责任编辑:彭凡 来源: 博客园
相关推荐

2009-09-10 11:26:59

C# form

2009-08-24 17:20:13

C#网络通信TCP连接

2012-12-24 14:40:54

iosjs

2011-03-10 09:07:47

liferayportlet

2021-12-16 16:20:57

GoWebSocketLinux

2009-11-11 10:43:49

Go语言Google

2010-03-18 19:06:35

Java socket

2010-02-01 13:08:46

C++函数指针C#托

2011-07-18 09:47:20

ModBusC#

2009-08-28 15:35:31

C#与VB.net

2009-09-04 15:57:49

C#实现汉字之间互换

2009-08-13 16:27:07

C#基于TCP协议

2009-08-28 10:08:02

C#数值类型之间转换

2015-03-03 13:47:34

HttpTCPIP

2010-03-09 10:59:42

Python语言教程

2009-08-21 15:59:22

服务端与客户端通信

2009-08-21 16:14:52

服务端与客户端通信

2019-12-26 09:28:34

TCPPython通信

2009-08-25 17:24:55

C#串口通信程序

2021-09-27 22:49:13

GoC 指针
点赞
收藏

51CTO技术栈公众号