Golang TCP通信案例
TCP服务端代码
package main
import (
"encoding/binary"
"encoding/hex"
"fmt"
"net"
)
type DataPacket struct {
Type string
Body string
}
func main() {
//绑定端口
tcpAddr, err := net.ResolveTCPAddr("tcp", ":19010")
if err != nil {
fmt.Println(err.Error())
}
//监听
listener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
fmt.Println(err.Error())
}
defer listener.Close()
//开始接收数据
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err.Error())
}
go Handler(conn)
}
}
func Handler(conn net.Conn) {
defer conn.Close()
//每次读取数据长度
buf := make([]byte, 256)
_, err := conn.Read(buf)
if err != nil {
return
}
result, Body := check(buf)
if result {
fmt.Printf("接收到报文内容:{%s}\n", hex.EncodeToString(Body))
}
}
func check(buf []byte) (bool, []byte) {
Length := DataLength(buf)
if Length < 3 || Length > 256 {
return false, nil
}
Body := buf[:Length]
return uint16(len(Body))-2 != Length, Body
}
func DataLength(buf []byte) uint16 {
return binary.BigEndian.Uint16(inversion(buf[:2])) + 2
}
//反转字节
func inversion(buf []byte) []byte {
for i := 0; i < len(buf)/2; i++ {
temp := buf[i]
buf[i] = buf[len(buf)-1-i]
buf[len(buf)-1-i] = temp
}
return buf
}
Go TCP客户端代码
package main
import (
"bufio"
"encoding/hex"
"fmt"
"net"
)
//客户端对象
type TcpClient struct {
connection *net.TCPConn
server *net.TCPAddr
stopChan chan struct{}
}
func main() {
tcpAddr, err := net.ResolveTCPAddr("tcp", ":19010")
if err != nil {
fmt.Println(err.Error())
return
}
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
fmt.Println(err.Error())
return
}
send(conn)
}
func send(conn *net.TCPConn) {
defer conn.Close()
decodeString, _ := hex.DecodeString("2300a78c070000000000000a00000000000000030000000000010618120250ba2700004eb0")
_, err := conn.Write(decodeString)
if err != nil {
fmt.Printf(err.Error())
}
}
// 接收数据包
func (client *TcpClient) receivePackets() {
reader := bufio.NewReader(client.connection)
for {
//承接上面说的服务器端的偷懒,我这里读也只是以\n为界限来读区分包
msg, err := reader.ReadString('\n')
if err != nil {
//在这里也请处理如果服务器关闭时的异常
close(client.stopChan)
break
}
fmt.Print(msg)
}
}
func (client *TcpClient) send() {
}
运行结果: