|
| 1 | +--- |
| 2 | +layout: default |
| 3 | +title: Quick Start with Runtime Library in Go |
| 4 | +grand_parent: Runtime Library |
| 5 | +parent: Runtime Library in Go |
| 6 | +nav_order: 2 |
| 7 | +--- |
| 8 | + |
| 9 | +# Quick Start |
| 10 | +This guide walks you through a few examples of using different modes of `water` Runtime Library. |
| 11 | + |
| 12 | +## Dialer Mode |
| 13 | +The code below demonstrates how to use `water` to create a dialer that connects to a remote server and send random bytes every 5 seconds. |
| 14 | + |
| 15 | +```go |
| 16 | +package main |
| 17 | + |
| 18 | +import ( |
| 19 | + "context" |
| 20 | + "crypto/rand" |
| 21 | + "flag" |
| 22 | + "fmt" |
| 23 | + "log" |
| 24 | + "net" |
| 25 | + "os" |
| 26 | + "time" |
| 27 | + |
| 28 | + "github.com/refraction-networking/water" // import the water package |
| 29 | + _ "github.com/refraction-networking/water/transport/v0" // explicitly enable WATM v0 |
| 30 | +) |
| 31 | + |
| 32 | +var ( |
| 33 | + remoteAddr = flag.String("raddr", "", "remote address to dial") |
| 34 | + wasmPath = flag.String("wasm", "", "path to wasm file") |
| 35 | + remoteConn net.Conn |
| 36 | +) |
| 37 | + |
| 38 | +func main() { |
| 39 | + flag.Parse() |
| 40 | + |
| 41 | + wasm, err := os.ReadFile(*wasmPath) |
| 42 | + if err != nil { |
| 43 | + panic(fmt.Sprintf("failed to read wasm file: %v", err)) |
| 44 | + } |
| 45 | + |
| 46 | + // start using W.A.T.E.R. API below this line, have fun! |
| 47 | + config := &water.Config{ |
| 48 | + TransportModuleBin: wasm, |
| 49 | + NetworkDialerFunc: net.Dial, // optional field, defaults to net.Dial |
| 50 | + } |
| 51 | + // configuring the standard out of the WebAssembly instance to inherit |
| 52 | + // from the parent process |
| 53 | + config.ModuleConfig().InheritStdout() |
| 54 | + config.ModuleConfig().InheritStderr() |
| 55 | + |
| 56 | + ctx := context.Background() |
| 57 | + // // optional: enable wazero logging |
| 58 | + // ctx = context.WithValue(ctx, experimental.FunctionListenerFactoryKey{}, |
| 59 | + // logging.NewHostLoggingListenerFactory(os.Stderr, logging.LogScopeFilesystem|logging.LogScopePoll|logging.LogScopeSock)) |
| 60 | + |
| 61 | + dialer, err := water.NewDialerWithContext(ctx, config) |
| 62 | + if err != nil { |
| 63 | + panic(fmt.Sprintf("failed to create dialer: %v", err)) |
| 64 | + } |
| 65 | + |
| 66 | + conn, err := dialer.DialContext(ctx, "tcp", *remoteAddr) |
| 67 | + if err != nil { |
| 68 | + panic(fmt.Sprintf("failed to dial: %v", err)) |
| 69 | + } |
| 70 | + defer conn.Close() |
| 71 | + // conn is a net.Conn that you are familiar with. |
| 72 | + // So effectively, W.A.T.E.R. API ends here and everything below |
| 73 | + // this line is just how you treat a net.Conn. |
| 74 | + |
| 75 | + remoteConn = conn |
| 76 | + |
| 77 | + worker() |
| 78 | +} |
| 79 | + |
| 80 | +func worker() { |
| 81 | + defer remoteConn.Close() |
| 82 | + |
| 83 | + log.Printf("Connected to %s", remoteConn.RemoteAddr()) |
| 84 | + chanMsgRecv := make(chan []byte, 4) // up to 4 messages in the buffer |
| 85 | + // start a goroutine to read data from the connection |
| 86 | + go func() { |
| 87 | + defer close(chanMsgRecv) |
| 88 | + buf := make([]byte, 1024) // 1 KiB |
| 89 | + for { |
| 90 | + n, err := remoteConn.Read(buf) |
| 91 | + if err != nil { |
| 92 | + log.Printf("read remoteConn: error %v, tearing down connection...", err) |
| 93 | + remoteConn.Close() |
| 94 | + return |
| 95 | + } |
| 96 | + chanMsgRecv <- buf[:n] |
| 97 | + } |
| 98 | + }() |
| 99 | + |
| 100 | + // start a ticker for sending message every 5 seconds |
| 101 | + ticker := time.NewTicker(5 * time.Second) |
| 102 | + defer ticker.Stop() |
| 103 | + |
| 104 | + var sendBuf []byte = make([]byte, 4) // 4 bytes per message |
| 105 | + for { |
| 106 | + select { |
| 107 | + case msg := <-chanMsgRecv: |
| 108 | + if msg == nil { |
| 109 | + return // connection closed |
| 110 | + } |
| 111 | + log.Printf("peer: %x\n", msg) |
| 112 | + case <-ticker.C: |
| 113 | + n, err := rand.Read(sendBuf) |
| 114 | + if err != nil { |
| 115 | + log.Printf("rand.Read: error %v, tearing down connection...", err) |
| 116 | + return |
| 117 | + } |
| 118 | + // print the bytes sending as hex string |
| 119 | + log.Printf("sending: %x\n", sendBuf[:n]) |
| 120 | + |
| 121 | + _, err = remoteConn.Write(sendBuf[:n]) |
| 122 | + if err != nil { |
| 123 | + log.Printf("write: error %v, tearing down connection...", err) |
| 124 | + return |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | +} |
| 129 | +``` |
| 130 | + |
| 131 | +## Listener Mode |
| 132 | +The code below demonstrates how to use `water` to create a listener that listens on a local address and accepts incoming connections then sends random bytes every 5 seconds. |
| 133 | + |
| 134 | +```go |
| 135 | +package main |
| 136 | + |
| 137 | +import ( |
| 138 | + "context" |
| 139 | + "crypto/rand" |
| 140 | + "flag" |
| 141 | + "fmt" |
| 142 | + "log" |
| 143 | + "net" |
| 144 | + "os" |
| 145 | + "time" |
| 146 | + |
| 147 | + "github.com/refraction-networking/water" |
| 148 | + _ "github.com/refraction-networking/water/transport/v0" |
| 149 | +) |
| 150 | + |
| 151 | +var ( |
| 152 | + localAddr = flag.String("laddr", "", "local address to listen on") |
| 153 | + wasmPath = flag.String("wasm", "", "path to wasm file") |
| 154 | +) |
| 155 | + |
| 156 | +func main() { |
| 157 | + flag.Parse() |
| 158 | + |
| 159 | + wasm, err := os.ReadFile(*wasmPath) |
| 160 | + if err != nil { |
| 161 | + panic(fmt.Sprintf("failed to read wasm file: %v", err)) |
| 162 | + } |
| 163 | + |
| 164 | + // start using W.A.T.E.R. API below this line, have fun! |
| 165 | + config := &water.Config{ |
| 166 | + TransportModuleBin: wasm, |
| 167 | + } |
| 168 | + // configuring the standard out of the WebAssembly instance to inherit |
| 169 | + // from the parent process |
| 170 | + config.ModuleConfig().InheritStdout() |
| 171 | + config.ModuleConfig().InheritStderr() |
| 172 | + |
| 173 | + ctx := context.Background() |
| 174 | + // // optional: enable wazero logging |
| 175 | + // ctx = context.WithValue(ctx, experimental.FunctionListenerFactoryKey{}, |
| 176 | + // logging.NewHostLoggingListenerFactory(os.Stderr, logging.LogScopeFilesystem|logging.LogScopePoll|logging.LogScopeSock)) |
| 177 | + |
| 178 | + lis, err := config.ListenContext(ctx, "tcp", *localAddr) |
| 179 | + if err != nil { |
| 180 | + panic(fmt.Sprintf("failed to listen: %v", err)) |
| 181 | + } |
| 182 | + defer lis.Close() |
| 183 | + log.Printf("Listening on %s:%s", lis.Addr().Network(), lis.Addr().String()) |
| 184 | + // lis is a net.Listener that you are familiar with. |
| 185 | + // So effectively, W.A.T.E.R. API ends here and everything below |
| 186 | + // this line is just how you treat a net.Listener. |
| 187 | + |
| 188 | + clientCntr := 0 |
| 189 | + for { |
| 190 | + conn, err := lis.Accept() |
| 191 | + if err != nil { |
| 192 | + panic(fmt.Sprintf("failed to accept: %v", err)) |
| 193 | + } |
| 194 | + |
| 195 | + // start a goroutine to handle the connection |
| 196 | + go handleConn(fmt.Sprintf("client#%d", clientCntr), conn) |
| 197 | + clientCntr++ |
| 198 | + } |
| 199 | +} |
| 200 | + |
| 201 | +func handleConn(peer string, conn net.Conn) { |
| 202 | + defer conn.Close() |
| 203 | + |
| 204 | + log.Printf("handling connection from/to %s(%s)", peer, conn.RemoteAddr()) |
| 205 | + chanMsgRecv := make(chan []byte, 4) // up to 4 messages in the buffer |
| 206 | + // start a goroutine to read data from the connection |
| 207 | + go func() { |
| 208 | + defer close(chanMsgRecv) |
| 209 | + buf := make([]byte, 1024) // 1 KiB |
| 210 | + for { |
| 211 | + // conn.SetReadDeadline(time.Now().Add(5 * time.Second)) |
| 212 | + n, err := conn.Read(buf) |
| 213 | + if err != nil { |
| 214 | + log.Printf("read %s: error %v, tearing down connection...", peer, err) |
| 215 | + conn.Close() |
| 216 | + return |
| 217 | + } |
| 218 | + chanMsgRecv <- buf[:n] |
| 219 | + } |
| 220 | + }() |
| 221 | + |
| 222 | + // start a ticker for sending message every 5 seconds |
| 223 | + ticker := time.NewTicker(5 * time.Second) |
| 224 | + defer ticker.Stop() |
| 225 | + |
| 226 | + var sendBuf []byte = make([]byte, 4) // 4 bytes per message |
| 227 | + for { |
| 228 | + select { |
| 229 | + case msg := <-chanMsgRecv: |
| 230 | + if msg == nil { |
| 231 | + log.Printf("read %s: connection closed, tearing down connection...", peer) |
| 232 | + return // connection closed |
| 233 | + } |
| 234 | + log.Printf("%s: %x\n", peer, msg) |
| 235 | + case <-ticker.C: |
| 236 | + n, err := rand.Read(sendBuf) |
| 237 | + if err != nil { |
| 238 | + log.Printf("rand.Read: error %v, tearing down connection...", err) |
| 239 | + return |
| 240 | + } |
| 241 | + // print the bytes sending as hex string |
| 242 | + log.Printf("sending: %x\n", sendBuf[:n]) |
| 243 | + |
| 244 | + _, err = conn.Write(sendBuf[:n]) |
| 245 | + if err != nil { |
| 246 | + log.Printf("write %s: error %v, tearing down connection...", peer, err) |
| 247 | + return |
| 248 | + } |
| 249 | + } |
| 250 | + } |
| 251 | +} |
| 252 | +``` |
0 commit comments