Go语言是Google推出的一种全新的编程语言,具有简洁的设计、强大的并发能力以及美好的编程体验。我本人也才接触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);
}
}
}
}