|
| 1 | +# golang-sample-with-tcp-udp-socket |
| 2 | + |
| 3 | + This repository is demo how to use tcp and udp socket in golang |
| 4 | + |
| 5 | +## tcp logic |
| 6 | + |
| 7 | +```golang |
| 8 | +func main() { |
| 9 | + // setup logger |
| 10 | + ctx := context.Background() |
| 11 | + ulog := logger.FromContext(ctx) |
| 12 | + // create tcp socket |
| 13 | + listener, err := net.Listen("tcp", config.AppConfig.ServerURI) |
| 14 | + if err != nil { |
| 15 | + ulog.ErrorContext(ctx, "failed to listen", slog.Any("addr", listener.Addr().String())) |
| 16 | + os.Exit(1) |
| 17 | + } |
| 18 | + defer listener.Close() |
| 19 | + |
| 20 | + for { |
| 21 | + // Accept an incoming connection |
| 22 | + conn, err := listener.Accept() |
| 23 | + if err != nil { |
| 24 | + ulog.ErrorContext(ctx, "failed to accept request", slog.Any("err", err)) |
| 25 | + } |
| 26 | + |
| 27 | + // Handle the connection |
| 28 | + go handleConnectionNonBlocking(ctx, conn) |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +// handleConnectionNonBlocking - nonblock reading with setup conn read/write timeout |
| 33 | +func handleConnectionNonBlocking(ctx context.Context, conn net.Conn) { |
| 34 | + hlog := logger.FromContext(ctx) |
| 35 | + defer conn.Close() |
| 36 | + for { |
| 37 | + // Set a deadline for reading data |
| 38 | + conn.SetReadDeadline(time.Now().Add(time.Second)) |
| 39 | + // Read from client |
| 40 | + buf := make([]byte, 1024) |
| 41 | + // block util read timeout |
| 42 | + n, err := conn.Read(buf) |
| 43 | + if err != nil { |
| 44 | + if netErr, ok := err.(net.Error); ok && netErr.Timeout() { |
| 45 | + // The read operation timeout, continue waiting for next read |
| 46 | + continue |
| 47 | + } else if !errors.Is(err, io.EOF) { |
| 48 | + // Other errors (client disconnected, etc) |
| 49 | + hlog.ErrorContext(ctx, "Connection closed", slog.Any("err", err)) |
| 50 | + break |
| 51 | + } |
| 52 | + } |
| 53 | + if n > 0 { |
| 54 | + msg := string(buf[:n]) |
| 55 | + hlog.InfoContext(ctx, "Received", slog.String("message", msg)) |
| 56 | + |
| 57 | + // Set a deadline for writing data |
| 58 | + conn.SetWriteDeadline(time.Now().Add(time.Second)) |
| 59 | + // Send a response to the client |
| 60 | + _, err = fmt.Fprintf(conn, "Echo - %s", msg) |
| 61 | + if err != nil { |
| 62 | + hlog.ErrorContext(ctx, "error writing to client", slog.Any("err", err)) |
| 63 | + break |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | +``` |
| 69 | +## udp logic |
| 70 | +```golang |
| 71 | +func main() { |
| 72 | + // setup logger |
| 73 | + ctx := context.Background() |
| 74 | + ulog := logger.FromContext(ctx) |
| 75 | + // setup connection socket with udp |
| 76 | + addr, err := net.ResolveUDPAddr("udp", config.AppConfig.ServerURI) |
| 77 | + if err != nil { |
| 78 | + ulog.InfoContext(ctx, "failed to resolve addr", slog.Any("err", err)) |
| 79 | + os.Exit(1) |
| 80 | + } |
| 81 | + conn, err := net.ListenUDP("udp", addr) |
| 82 | + if err != nil { |
| 83 | + ulog.ErrorContext(ctx, "failed to listen udp", slog.Any("err", err)) |
| 84 | + os.Exit(2) |
| 85 | + } |
| 86 | + defer conn.Close() |
| 87 | + |
| 88 | + for { |
| 89 | + // Read a message from the client |
| 90 | + buf := make([]byte, 1024) |
| 91 | + n, clientAddr, err := conn.ReadFromUDP(buf) |
| 92 | + if err != nil { |
| 93 | + ulog.ErrorContext(ctx, "Error reading", slog.Any("err", err)) |
| 94 | + continue |
| 95 | + } |
| 96 | + |
| 97 | + if n > 0 { |
| 98 | + msg := string(buf[:n]) |
| 99 | + // Print received message |
| 100 | + ulog.InfoContext(ctx, "Received message", slog.Any("clientAddr", clientAddr), slog.String("message", msg)) |
| 101 | + // Send response to the client |
| 102 | + _, err = conn.WriteToUDP([]byte("Hey client!"), clientAddr) |
| 103 | + if err != nil { |
| 104 | + ulog.ErrorContext(ctx, "error writing", slog.Any("err", err)) |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | +} |
| 109 | +``` |
0 commit comments