Google GO與C#之間的TCP通信案例
我本人也才接觸GO兩個多月的曆史,看了幾本英文教程,讀了些Github上麵的源碼,但已經被GO的語言的簡潔和強大的並發能力所吸收,也打算繼續深入的學習,並應用到自己的工作之中。GO語言目前主要適用於服務端的開發,我參考了一些網絡上的教程,做了一些TCP服務端的小練習,其中服務端用GO語言開發,客戶端采用C#。具體參考如下的代碼:https://github.com/yfl8910/gotcpserver
效果圖如下:
服務端代碼:
- package main
- import (
- "net"
- "fmt"
- )
- var ( maxRead = 25
- msgStop = []byte("cmdStop")
- msgStart = []byte("cmdContinue")
- )
- func main() {
- hostAndPort := "localhost:54321"
- listener := initServer(hostAndPort)
- for {
- conn, err := listener.Accept()
- checkError(err, "Accept: ")
- go connectionHandler(conn)
- }
- }
- func initServer(hostAndPort string) *net.TCPListener {
- serverAddr, err := net.ResolveTCPAddr("tcp", hostAndPort)
- checkError(err, "Resolving address:port failed: '" + hostAndPort + "'")
- //listener, err := net.ListenTCP("tcp", serverAddr)
- listener, err := net.ListenTCP("tcp", serverAddr)
- checkError(err, "ListenTCP: ")
- println("Listening to: ", listener.Addr().String())
- return listener
- }
- func connectionHandler(conn net.Conn) {
- connFrom := conn.RemoteAddr().String()
- println("Connection from: ", connFrom)
- talktoclients(conn)
- for {
- var ibuf []byte = make([]byte, maxRead + 1)
- length, err := conn.Read(ibuf[0:maxRead])
- ibuf[maxRead] = 0 // to prevent overflow
- switch err {
- case nil:
- handleMsg(length, err, ibuf)
- default:
- goto DISCONNECT
- }
- }
- DISCONNECT:
- err := conn.Close()
- println("Closed connection:" , connFrom)
- checkError(err, "Close:" )
- }
- func talktoclients(to net.Conn) {
- wrote, err := to.Write(msgStart)
- checkError(err, "Write: wrote " + string(wrote) + " bytes.")
- }
- func handleMsg(length int, err error, msg []byte) {
- if length > 0 {
- for i := 0; ; i++ {
- if msg[i] == 0 {
- break
- }
- }
- fmt.Printf("Received data: %v", string(msg[0:length]))
- fmt.Println(" length:",length)
- }
- }
- func checkError(error error, info string) {
- if error != nil {
- panic("ERROR: " + info + " " + error.Error()) // terminate program
- }
- }
客戶端代碼:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- namespace TcpClient
- {
- public partial class Form1 : Form
- {
- private IPAddress _ipServer; //服務器IP
- private IPEndPoint _myServer; //服務器終端
- private Socket _connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//連接套接字
- private int _port; //端口
- private Thread receiveThread = null;
- public Form1()
- {
- InitializeComponent();
- }
- private bool ValidateInfo() //檢驗所填信息是否合法
- {
- if (!IPAddress.TryParse(txtbxIP.Text, out _ipServer))
- {
- MessageBox.Show("IP地址不合法!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
- return false;
- }
- if (!int.TryParse(txtbxPortNum.Text, out _port))
- {
- MessageBox.Show("端口號不合法!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
- return false;
- }
- else
- {
- if (_port < 1024 || _port > 65535)
- {
- MessageBox.Show("端口號不合法!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
- return false;
- }
- }
- return true;
- }
- private bool ConnectServer() //連接服務器
- {
- try
- {
- _connectSocket.Connect(_myServer);
- _connectSocket.Send(System.Text.Encoding.UTF8.GetBytes(txtbxUser.Text.ToString()));
- return true;
- }
- catch
- {
- MessageBox.Show("服務器連接異常", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return false;
- }
- }
- private void button1_Click(object sender, EventArgs e)
- {
- try
- {
- _connectSocket.Send(System.Text.Encoding.UTF8.GetBytes(comboBox1.Text.ToString()));
- }
- catch
- {
- MessageBox.Show("服務器連接異常", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- private void button3_Click(object sender, EventArgs e)
- {
- if (!ValidateInfo())
- {
- return;
- }
- _myServer = new IPEndPoint(_ipServer, _port);
- if (ConnectServer() == true)
- {
- MessageBox.Show("連接成功!");
- }
- }
- private void button2_Click(object sender, EventArgs e)
- {
- this.Close();
- }
- private void button4_Click(object sender, EventArgs e)
- {
- for (int i = 0; i < 1000; i++) {
- Socket _connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- _connectSocket.Connect(_myServer);
- _connectSocket.Send(System.Text.Encoding.UTF8.GetBytes(comboBox1.Text.ToString()+i));
- Thread.Sleep(2);
- }
- }
- }
- }
最後更新:2017-04-03 22:30:58