1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| package common import ( "net" "errors" "bytes" "encoding/binary" ) type PkgHeader struct { HeaderFlag [2]byte DataLength uint32 } const( HeaderLength = 6 ) const( SOCKET_ERROR_CLIENT_CLOSED = "Client has been closed" SOCKET_ERROR_SERVER_CLOSED = "Server has been closed" SOCKET_ERROR_TIMEOUT = "Timeout" ) type SocketUtil struct { Conn net.Conn } func (fd *SocketUtil) Init(conn net.Conn){ fd.Conn = conn } func (fd *SocketUtil) WritePkg(data []byte)(int, error){ if fd == nil { return -1, errors.New(SOCKET_ERROR_SERVER_CLOSED) } if len(data) == 0{ return 0, nil } buff := bytes.NewBuffer([]byte{}) binary.Write(buff, binary.BigEndian, []byte{0xaa, 0xbb}) binary.Write(buff, binary.BigEndian, uint32(len(data))) binary.Write(buff, binary.BigEndian, data) allBytes := buff.Bytes() return fd.writeNByte(allBytes) } func (fd *SocketUtil) ReadPkg()([]byte, error){ if fd == nil || fd.Conn == nil{ return nil, errors.New(SOCKET_ERROR_SERVER_CLOSED) } head, err := fd.readHead() if err != nil{ return nil, err } if head.HeaderFlag != [2]byte{0xaa, 0xbb}{ return nil, errors.New("Head package error") } datas, err := fd.readNByte(head.DataLength) if err != nil{ return nil, err } return datas, nil } func (fd *SocketUtil) readHead()(*PkgHeader, error){ data, err := fd.readNByte(HeaderLength) if err != nil{ return nil, err } h := PkgHeader{} buff := bytes.NewBuffer(data) binary.Read(buff, binary.BigEndian, &h.HeaderFlag) binary.Read(buff, binary.BigEndian, &h.DataLength) return &h, nil } func (fd * SocketUtil) readNByte(n uint32)([]byte, error){ data := make([]byte, n) for x := 0; x < int(n) ;{ length, err := fd.Conn.Read(data[x:]) if length == 0{ return nil, errors.New(SOCKET_ERROR_CLIENT_CLOSED) } if err != nil{ return nil, err } x += length } return data, nil } func (fd *SocketUtil) writeNByte(data []byte)(int, error){ n, err := fd.Conn.Write(data) if err != nil{ return -1, err }else{ return n, nil } } func (fd *SocketUtil) Close(){ fd.Conn.Close() }
|