ruk·si

🐹 Go
Socket Server

Updated at 2015-10-24 12:09

Simple Unix stream socket server and client example.

Server

package main

import (
    "fmt"
    "io"
    "net"
    "os"
)

func echoServer(conn net.Conn, clientNumber int) {
    defer conn.Close()
    for {

        var buf [1024]byte
        raw, err := conn.Read(buf[:])
        if err == io.EOF {
            return
        }
        if err != nil {
            panic(err)
        }
        request := string(buf[:raw])
        fmt.Printf("Received (%d): %s\n", clientNumber, request)

        response := fmt.Sprintf("ok %d", clientNumber)
        _, err = conn.Write([]byte(response))
        if err != nil {
            panic(err)
        }

    }
}

func main() {

    socketType := "unix"
    socketFile := "/tmp/my-socket.sock"
    if _, err := os.Stat(socketFile); err == nil {
        // Socket file doesn't get removed if you Ctrl+C out
        os.Remove(socketFile)
    }
    socketEndpoint := &net.UnixAddr{socketFile, socketType}

    listener, err := net.ListenUnix(socketType, socketEndpoint)
    if err != nil {
        panic(err)
    }
    defer os.Remove(socketFile)

    fmt.Printf("Listening to %s\n", socketFile)

    clientCounter := 0
    for {
        // Accept a single connection and start serving to it
        conn, err := listener.Accept()
        if err != nil {
            panic(err)
        }
        clientCounter++
        go echoServer(conn, clientCounter)
    }

}

Client

package main

import (
    "fmt"
    "io"
    "net"
    "time"
)

func createConnection() net.Conn {
    socketType := "unix"
    socketFile := "/tmp/my-socket.sock"
    socketEndpoint := &net.UnixAddr{socketFile, socketType}

    conn, err := net.DialUnix(socketType, nil, socketEndpoint)
    if err != nil {
        panic(err)
    }
    return conn
}

func handleResponses(r io.Reader) {
    buf := make([]byte, 1024)
    for {
        n, err := r.Read(buf[:])
        if err != nil {
            return
        }
        fmt.Printf("Received: %s\n", string(buf[0:n]))
    }
}

func sendMessages(conn net.Conn) {
    for {
        message := "{}"
        _, err := conn.Write([]byte(message))
        if err != nil {
            fmt.Printf("Error: %s\n", err)
            break
        }
        fmt.Printf("Sent: %s\n", message)
        time.Sleep(1 * time.Second)
        //
    }
}

func main() {
    conn := createConnection()
    defer conn.Close()
    go handleResponses(conn)
    sendMessages(conn)
}

Sources