DEFLATE is suitable for transmitting compressed data across the network.
()
| 157 | |
| 158 | // DEFLATE is suitable for transmitting compressed data across the network. |
| 159 | func Example_synchronization() { |
| 160 | var wg sync.WaitGroup |
| 161 | defer wg.Wait() |
| 162 | |
| 163 | // Use io.Pipe to simulate a network connection. |
| 164 | // A real network application should take care to properly close the |
| 165 | // underlying connection. |
| 166 | rp, wp := io.Pipe() |
| 167 | |
| 168 | // Start a goroutine to act as the transmitter. |
| 169 | wg.Add(1) |
| 170 | go func() { |
| 171 | defer wg.Done() |
| 172 | defer wp.Close() |
| 173 | |
| 174 | zw, err := flate.NewWriter(wp, flate.BestSpeed) |
| 175 | if err != nil { |
| 176 | log.Fatal(err) |
| 177 | } |
| 178 | |
| 179 | b := make([]byte, 256) |
| 180 | for m := range strings.FieldsSeq("A long time ago in a galaxy far, far away...") { |
| 181 | // We use a simple framing format where the first byte is the |
| 182 | // message length, followed the message itself. |
| 183 | b[0] = uint8(copy(b[1:], m)) |
| 184 | |
| 185 | if _, err := zw.Write(b[:1+len(m)]); err != nil { |
| 186 | log.Fatal(err) |
| 187 | } |
| 188 | |
| 189 | // Flush ensures that the receiver can read all data sent so far. |
| 190 | if err := zw.Flush(); err != nil { |
| 191 | log.Fatal(err) |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | if err := zw.Close(); err != nil { |
| 196 | log.Fatal(err) |
| 197 | } |
| 198 | }() |
| 199 | |
| 200 | // Start a goroutine to act as the receiver. |
| 201 | wg.Add(1) |
| 202 | go func() { |
| 203 | defer wg.Done() |
| 204 | |
| 205 | zr := flate.NewReader(rp) |
| 206 | |
| 207 | b := make([]byte, 256) |
| 208 | for { |
| 209 | // Read the message length. |
| 210 | // This is guaranteed to return for every corresponding |
| 211 | // Flush and Close on the transmitter side. |
| 212 | if _, err := io.ReadFull(zr, b[:1]); err != nil { |
| 213 | if err == io.EOF { |
| 214 | break // The transmitter closed the stream |
| 215 | } |
| 216 | log.Fatal(err) |
nothing calls this directly
no test coverage detected
searching dependent graphs…