evio/examples/echo-server/main.go

56 lines
1.3 KiB
Go
Raw Normal View History

2017-11-02 18:08:18 +03:00
// Copyright 2017 Joshua J Baker. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
2017-07-04 06:39:18 +03:00
package main
import (
2017-11-03 04:31:36 +03:00
"flag"
"fmt"
2017-10-28 03:01:03 +03:00
"log"
"strings"
2017-07-04 06:39:18 +03:00
2017-10-29 00:58:59 +03:00
"github.com/tidwall/evio"
2017-07-04 06:39:18 +03:00
)
func main() {
2017-11-03 04:31:36 +03:00
var port int
2017-11-14 21:42:15 +03:00
var udp bool
var trace bool
var reuseport bool
2017-11-03 04:31:36 +03:00
flag.IntVar(&port, "port", 5000, "server port")
2017-11-14 21:42:15 +03:00
flag.BoolVar(&udp, "udp", false, "listen on udp")
flag.BoolVar(&reuseport, "reuseport", false, "reuseport (SO_REUSEPORT)")
flag.BoolVar(&trace, "trace", false, "print packets to console")
2017-11-03 04:31:36 +03:00
flag.Parse()
2017-10-28 03:01:03 +03:00
2017-11-03 04:31:36 +03:00
var events evio.Events
2017-11-08 02:12:16 +03:00
events.Serving = func(srv evio.Server) (action evio.Action) {
2017-11-03 04:31:36 +03:00
log.Printf("echo server started on port %d", port)
if reuseport {
log.Printf("reuseport")
}
2017-11-03 04:31:36 +03:00
return
}
2017-11-08 02:12:16 +03:00
events.Opened = func(id int, info evio.Info) (out []byte, opts evio.Options, action evio.Action) {
2017-11-14 21:42:15 +03:00
// log.Printf("opened: %d: %+v", id, info)
2017-11-03 04:31:36 +03:00
return
}
events.Closed = func(id int, err error) (action evio.Action) {
2017-11-14 21:42:15 +03:00
// log.Printf("closed: %d", id)
2017-10-28 03:01:03 +03:00
return
}
2017-10-29 00:58:59 +03:00
events.Data = func(id int, in []byte) (out []byte, action evio.Action) {
if trace {
log.Printf("%s", strings.TrimSpace(string(in)))
}
2017-10-28 03:01:03 +03:00
out = in
return
}
2017-11-14 21:42:15 +03:00
scheme := "tcp"
if udp {
scheme = "udp"
}
log.Fatal(evio.Serve(events, fmt.Sprintf("%s://:%d?reuseport=%t", scheme, port, reuseport)))
2017-07-04 06:39:18 +03:00
}