-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
56 lines (46 loc) · 1.16 KB
/
server.go
File metadata and controls
56 lines (46 loc) · 1.16 KB
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
// SPDX-License-Identifier: AGPL-3.0-or-later
package dataexchange
import (
"log/slog"
"net"
"github.com/TeoSlayer/pilotprotocol/pkg/driver"
"github.com/TeoSlayer/pilotprotocol/pkg/protocol"
)
// Handler is called for each incoming frame on a connection.
type Handler func(conn net.Conn, frame *Frame)
// Server listens on port 1001 and dispatches incoming frames to a handler.
type Server struct {
driver *driver.Driver
listener *driver.Listener
handler Handler
}
// NewServer creates a data exchange server.
func NewServer(d *driver.Driver, handler Handler) *Server {
return &Server{driver: d, handler: handler}
}
// ListenAndServe binds port 1001 and starts accepting connections.
func (s *Server) ListenAndServe() error {
ln, err := s.driver.Listen(protocol.PortDataExchange)
if err != nil {
return err
}
s.listener = ln
slog.Info("dataexchange listening", "port", protocol.PortDataExchange)
for {
conn, err := ln.Accept()
if err != nil {
return err
}
go s.handleConn(conn)
}
}
func (s *Server) handleConn(conn net.Conn) {
defer conn.Close()
for {
frame, err := ReadFrame(conn)
if err != nil {
return
}
s.handler(conn, frame)
}
}