[GoLang]GO语言编写的简易TCP服务端、客户端

客户端程序:

package main

import (
	"net"
	"os"
	"fmt"
	"io"
)

//缓冲区大小
const BUFFSIZE = 1024

//定义消息缓冲区
var buff = make([]byte, BUFFSIZE)

//链接处理
func handleConn(tcpConn *net.TCPConn, addr string) {
	if tcpConn == nil {
		//fmt.Println()
		return
	}
	for{
		n, err := tcpConn.Read(buff)
		if err == io.EOF {
			fmt.Printf("远程链接:%s已经关闭!\n", tcpConn.RemoteAddr().String())
			return
		}
		handleError(err)
		if string(buff[:n]) == "exit" {
			fmt.Printf("远程链接:%s退出!\n", tcpConn.RemoteAddr().String())
		}
		if n > 0 {
			fmt.Printf("%s发来消息:%s", addr, string(buff[:n]))
		}
	}
}

func handleError(err error) {
	if err == nil {
		return
	}
	fmt.Printf("错误:%s\n", err.Error())
}

func main() {

	//判断命令行参数是否错误
	if len(os.Args) != 2 {
		fmt.Printf("调用参数错误,程序中断!\n")
		return
	}

	//获取通讯端口
	port := os.Args[1]

	//原型:func ResolveTCPAddr(net, addr string) (*TCPAddr, error) ResolveTCPAddr parses addr as a TCP address
	//分解ip为TCP地址
	tcpAddr, err := net.ResolveTCPAddr("tcp4", "localhost:" + port)
	handleError(err)
	if err != nil {
		return
	}

	//原型:func ListenTCP(net string, laddr *TCPAddr) (*TCPListener, error) ListenTCP announces on the TCP address laddr and returns a TCP listener.
	//通过TCP地址返回一个TCP监听
	tcpListener, err := net.ListenTCP("tcp4", tcpAddr)
	handleError(err)
	if err != nil {
		return
	}

	fmt.Printf("启动监听,等待链接!\n")

	//延迟,监听关闭
	defer tcpListener.Close()

	for {
		//func (l *TCPListener) AcceptTCP() (*TCPConn, error) AcceptTCP accepts the next incoming call and returns the new connection.
		//等待下一个访问并返回一个新链接
		tcpConn, err := tcpListener.AcceptTCP()
		handleError(err)
		if err != nil {
			return
		}

		fmt.Printf("客户端:%s已连接!\n", tcpConn.RemoteAddr().String())
		//延迟,关闭链接
		defer tcpConn.Close()
		//启动一个连接处理线程
		go handleConn(tcpConn, tcpConn.RemoteAddr().String())
	}
}

服务端程序:

package main

import (
	"net"
	"os"
	"fmt"
	"bufio"
)

const BUFFSIZE = 1024
var buff = make([]byte, BUFFSIZE)

func handleError(err error) {
	if err == nil {
		return
	}
	fmt.Printf("错误:%s\n", err.Error())
}

func main() {
	if len(os.Args) != 2 {
		fmt.Printf("参数错误, 程序中断!\n")
		return
	}
	port := os.Args[1]
	tcpAddr, err := net.ResolveTCPAddr("tcp4", "localhost:" + port)
	handleError(err)
	tcpConn, err := net.DialTCP("tcp4", nil, tcpAddr)
	handleError(err)

	fmt.Printf("连接成功,请输入信息!\n")

	reader := bufio.NewReader(os.Stdin)
	continued := true
	inputStr := ""

	for(continued){
		n, err := reader.Read(buff)
		handleError(err)
		if n > 0 {
			k, _ := tcpConn.Write(buff[:n])
			if k > 0 {
				inputStr = string(buff[:n])
				fmt.Printf("发送消息:%s", inputStr)
				if inputStr == "exit\n" {
					continued = false
				}
			}
		}
	}
}

服务端:

[GoLang]GO语言编写的简易TCP服务端、客户端_第1张图片

客户端:

[GoLang]GO语言编写的简易TCP服务端、客户端_第2张图片

你可能感兴趣的:(GoLang)