socket

package
v1.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 23, 2025 License: Apache-2.0 Imports: 5 Imported by: 2

README

Socket

TCP/UDP socket client and server implementations.

Overview

The socket package provides simplified network programming with high-level abstractions for socket servers and clients. It handles connection management, concurrent client handling, and resource cleanup automatically.

Features

  • TCP/UDP Server - Accept and handle concurrent connections
  • TCP/UDP Client - Connect, read, and write operations
  • Connection Pooling - Configurable client pool size
  • Concurrent Handling - Automatic goroutine management
  • Resource Cleanup - Graceful shutdown and connection closing

Installation

go get -u github.com/common-library/go/socket

Quick Start

Server
server := &socket.Server{}
err := server.Start("tcp", ":8080", 100,
    func(client socket.Client) {
        data, _ := client.Read(1024)
        client.Write("Echo: " + data)
    },
    func(err error) {
        log.Printf("Accept error: %v", err)
    },
)
Client
client := &socket.Client{}
client.Connect("tcp", "localhost:8080")
client.Write("Hello")
data, _ := client.Read(1024)
client.Close()

API Reference

Server Type
type Server struct {
    // Internal fields
}
Server Methods
Start
func (s *Server) Start(network, address string, clientPoolSize int,
    acceptSuccessFunc func(client Client), 
    acceptFailureFunc func(err error)) error

Starts the socket server.

Stop
func (s *Server) Stop() error

Gracefully stops the server.

GetCondition
func (s *Server) GetCondition() bool

Returns server running state.

Client Type
type Client struct {
    // Internal fields
}
Client Methods
Connect
func (c *Client) Connect(network, address string) error

Connects to a remote address.

Read
func (c *Client) Read(recvSize int) (string, error)

Reads data from the connection.

Write
func (c *Client) Write(data string) (int, error)

Writes data to the connection.

Close
func (c *Client) Close() error

Closes the connection.

GetLocalAddr
func (c *Client) GetLocalAddr() net.Addr

Returns the local address.

GetRemoteAddr
func (c *Client) GetRemoteAddr() net.Addr

Returns the remote address.

Complete Examples

TCP Echo Server
package main

import (
    "log"
    "os"
    "os/signal"
    "syscall"
    "github.com/common-library/go/socket"
)

func main() {
    server := &socket.Server{}
    
    err := server.Start("tcp", ":8080", 100,
        func(client socket.Client) {
            log.Printf("Client connected: %v", client.GetRemoteAddr())
            
            for {
                data, err := client.Read(1024)
                if err != nil {
                    log.Printf("Read error: %v", err)
                    break
                }
                
                log.Printf("Received: %s", data)
                client.Write("Echo: " + data)
            }
        },
        func(err error) {
            log.Printf("Accept error: %v", err)
        },
    )
    
    if err != nil {
        log.Fatal(err)
    }
    
    log.Println("Server started on :8080")
    
    // Wait for interrupt
    sigChan := make(chan os.Signal, 1)
    signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
    <-sigChan
    
    log.Println("Shutting down...")
    server.Stop()
}
TCP Client
package main

import (
    "fmt"
    "log"
    "github.com/common-library/go/socket"
)

func main() {
    client := &socket.Client{}
    
    err := client.Connect("tcp", "localhost:8080")
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()
    
    fmt.Printf("Connected to %v\n", client.GetRemoteAddr())
    
    // Send message
    _, err = client.Write("Hello, Server!")
    if err != nil {
        log.Fatal(err)
    }
    
    // Receive response
    data, err := client.Read(1024)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("Server response: %s\n", data)
}
Chat Server
package main

import (
    "fmt"
    "log"
    "sync"
    "github.com/common-library/go/socket"
)

var (
    clients   = make(map[string]socket.Client)
    clientsMu sync.Mutex
)

func broadcast(message string, sender socket.Client) {
    clientsMu.Lock()
    defer clientsMu.Unlock()
    
    for _, client := range clients {
        if client.GetRemoteAddr() != sender.GetRemoteAddr() {
            client.Write(message)
        }
    }
}

func main() {
    server := &socket.Server{}
    
    server.Start("tcp", ":8080", 100,
        func(client socket.Client) {
            addr := client.GetRemoteAddr().String()
            
            clientsMu.Lock()
            clients[addr] = client
            clientsMu.Unlock()
            
            log.Printf("Client joined: %s", addr)
            broadcast(fmt.Sprintf("%s joined the chat", addr), client)
            
            defer func() {
                clientsMu.Lock()
                delete(clients, addr)
                clientsMu.Unlock()
                
                broadcast(fmt.Sprintf("%s left the chat", addr), client)
                log.Printf("Client left: %s", addr)
            }()
            
            for {
                data, err := client.Read(1024)
                if err != nil {
                    break
                }
                
                message := fmt.Sprintf("%s: %s", addr, data)
                log.Println(message)
                broadcast(message, client)
            }
        },
        nil,
    )
    
    log.Println("Chat server started on :8080")
    select {}
}

Best Practices

1. Set Appropriate Pool Size
// Good: Based on expected load
server.Start("tcp", ":8080", 100, ...) // 100 concurrent connections

// Avoid: Too small
server.Start("tcp", ":8080", 5, ...)   // May block under load
2. Handle Read/Write Errors
// Good: Check errors
data, err := client.Read(1024)
if err != nil {
    log.Printf("Read error: %v", err)
    return
}

// Avoid: Ignore errors
data, _ := client.Read(1024)
3. Always Close Connections
// Good: Defer close
client := &socket.Client{}
err := client.Connect("tcp", "localhost:8080")
if err == nil {
    defer client.Close()
}

// Avoid: Forget to close
client.Connect("tcp", "localhost:8080")
// No close - connection leak

Dependencies

  • net - Go standard library
  • sync - Go standard library
  • sync/atomic - Go standard library

Further Reading

Documentation

Overview

Package socket provides TCP/UDP socket client and server implementations.

This package simplifies network programming with high-level abstractions for socket servers and clients, supporting concurrent connection handling and automatic resource management.

Features

  • TCP and UDP socket client
  • Simple connect, read, write operations
  • Automatic connection management
  • Local and remote address access
  • Resource cleanup

Basic Client Example

client := &socket.Client{}
err := client.Connect("tcp", "localhost:8080")
client.Write("Hello")
data, _ := client.Read(1024)
client.Close()

Package socket provides TCP/UDP socket client and server implementations.

This package simplifies network programming with high-level abstractions for socket servers and clients, supporting concurrent connection handling and automatic resource management.

Features

  • TCP and UDP socket server
  • Concurrent client connection handling
  • Client connection pooling
  • Automatic resource cleanup
  • Custom accept success/failure handlers

Basic Server Example

server := &socket.Server{}
err := server.Start("tcp", ":8080", 100,
    func(client socket.Client) {
        data, _ := client.Read(1024)
        client.Write("Response: " + data)
    },
    func(err error) {
        log.Printf("Accept error: %v", err)
    },
)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a struct that provides client related methods.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection.

Returns

  • error: Error if close fails, nil on success

Examples

err := client.Close()

func (*Client) Connect

func (c *Client) Connect(network, address string) error

Connect establishes a connection to the remote address.

Parameters

  • network: Network type ("tcp", "tcp4", "tcp6", "udp", "udp4", "udp6", "unix")
  • address: Remote address (e.g., "localhost:8080", "192.168.1.1:9000")

Returns

  • error: Error if connection fails, nil on success

Examples

client := &socket.Client{}
err := client.Connect("tcp", "localhost:8080")

func (*Client) GetLocalAddr

func (c *Client) GetLocalAddr() net.Addr

GetLocalAddr returns the local network address.

Returns

  • net.Addr: Local address, or nil if not connected

Examples

addr := client.GetLocalAddr()
if addr != nil {
    fmt.Println(addr.String())
}

func (*Client) GetRemoteAddr

func (c *Client) GetRemoteAddr() net.Addr

GetRemoteAddr returns the remote network address.

Returns

  • net.Addr: Remote address, or nil if not connected

Examples

addr := client.GetRemoteAddr()
if addr != nil {
    fmt.Println(addr.String())
}

func (*Client) Read

func (c *Client) Read(recvSize int) (string, error)

Read reads data from the connection.

Parameters

  • recvSize: Maximum bytes to read (buffer size)

Returns

  • string: Received data
  • error: Error if read fails, nil on success

Examples

data, err := client.Read(1024)
if err != nil {
    log.Fatal(err)
}
fmt.Println(data)

func (*Client) Write

func (c *Client) Write(data string) (int, error)

Write writes data to the connection.

Parameters

  • data: Text data to write

Returns

  • int: Number of bytes written
  • error: Error if write fails, nil on success

Examples

n, err := client.Write("Hello, Server!")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Wrote %d bytes\n", n)

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a struct that provides server related methods.

func (*Server) GetCondition

func (s *Server) GetCondition() bool

GetCondition returns the server running state.

Returns

  • bool: true if server is running, false if stopped

Examples

if server.GetCondition() {
    fmt.Println("Server is running")
}

func (*Server) Start

func (s *Server) Start(network, address string, clientPoolSize int, acceptSuccessFunc func(client Client), acceptFailureFunc func(err error)) error

Start initializes and starts the socket server.

This method creates a listener on the specified network and address, accepting incoming connections and handling them concurrently using a pool of goroutines.

Parameters

  • network: Network type ("tcp", "tcp4", "tcp6", "udp", "udp4", "udp6", "unix")
  • address: Listen address (e.g., ":8080", "127.0.0.1:8080")
  • clientPoolSize: Maximum concurrent connections to buffer
  • acceptSuccessFunc: Callback for each accepted connection
  • acceptFailureFunc: Callback for accept errors

Returns

  • error: Error if server start fails, nil on success

Behavior

The server:

  • Stops any existing server instance
  • Creates a listener on the specified address
  • Accepts connections in a background goroutine
  • Spawns a goroutine for each connection (up to clientPoolSize buffered)
  • Calls acceptSuccessFunc for each connection
  • Calls acceptFailureFunc for accept errors (if not nil)

Examples

Basic TCP echo server:

server := &socket.Server{}
err := server.Start("tcp", ":8080", 100,
    func(client socket.Client) {
        data, _ := client.Read(1024)
        client.Write("Echo: " + data)
    },
    func(err error) {
        log.Printf("Error: %v", err)
    },
)

func (*Server) Stop

func (s *Server) Stop() error

Stop gracefully shuts down the socket server.

This method stops accepting new connections, waits for all active client handlers to complete, and closes the listener.

Returns

  • error: Error if shutdown fails, nil on successful shutdown

Behavior

The shutdown process:

  1. Sets condition to false (stops accepting)
  2. Waits for all job goroutines to complete
  3. Waits for channel to drain
  4. Closes the listener

Examples

err := server.Stop()
if err != nil {
    log.Printf("Stop error: %v", err)
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL