tcp

package
v1.2.4 Latest Latest
Warning

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

Go to latest
Published: Jan 1, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

README

TCP Socket Package

Package providing TCP socket client and server implementation for Go.

Features

  • TCP Socket Client: Simple connect, read, write operations
  • TCP Socket Server: Concurrent connection handling and automatic resource management
  • Concurrency Support: Handle multiple client connections simultaneously
  • Automatic Resource Cleanup: Automatic connection and resource release
  • Address Information Access: Query local and remote addresses

Installation

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

Usage Examples

TCP Client
package main

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

func main() {
    client := &tcp.Client{}
    
    // Connect to server
    err := client.Connect("tcp", "localhost:8080")
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()
    
    // Write data
    n, err := client.Write("Hello, Server!")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Sent %d bytes\n", n)
    
    // Read data
    data, err := client.Read(1024)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Received: %s\n", data)
    
    // Address information
    fmt.Printf("Local: %s\n", client.GetLocalAddr())
    fmt.Printf("Remote: %s\n", client.GetRemoteAddr())
}
TCP Server
package main

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

func main() {
    server := &tcp.Server{}
    
    // Connection handler
    acceptSuccessFunc := func(client tcp.Client) {
        // Read data from client
        data, err := client.Read(1024)
        if err != nil {
            log.Printf("Read error: %v", err)
            return
        }
        
        // Echo response
        _, err = client.Write("Echo: " + data)
        if err != nil {
            log.Printf("Write error: %v", err)
        }
    }
    
    // Connection failure handler
    acceptFailureFunc := func(err error) {
        log.Printf("Accept error: %v", err)
    }
    
    // Start server
    err := server.Start("tcp", ":8080", 100, acceptSuccessFunc, acceptFailureFunc)
    if err != nil {
        log.Fatal(err)
    }
    
    // Wait until server stops
    // (In reality, signal handling etc. should be added)
    select {}
}
Multi-Client Handling Example
package main

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

func main() {
    server := &tcp.Server{}
    
    acceptSuccessFunc := func(client tcp.Client) {
        defer client.Close()
        
        // Send welcome message
        client.Write("Welcome to the server!\n")
        
        // Process client requests
        for {
            data, err := client.Read(1024)
            if err != nil {
                break
            }
            
            // Simple protocol processing
            response := processRequest(data)
            client.Write(response)
        }
    }
    
    acceptFailureFunc := func(err error) {
        log.Printf("Connection error: %v", err)
    }
    
    // Handle maximum 1000 concurrent connections
    err := server.Start("tcp", ":8080", 1000, acceptSuccessFunc, acceptFailureFunc)
    if err != nil {
        log.Fatal(err)
    }
    defer server.Stop()
    
    fmt.Println("Server is running on :8080")
    select {}
}

func processRequest(data string) string {
    return fmt.Sprintf("Processed: %s\n", data)
}

API Documentation

Client
Connect(network, address string) error

Establishes a connection to a remote address.

  • network: Network type ("tcp", "tcp4", "tcp6", "unix")
  • address: Remote address (e.g., "localhost:8080", "192.168.1.1:9000")
Read(recvSize int) (string, error)

Reads data from the connection.

  • recvSize: Maximum number of bytes to read (buffer size)
  • return: Received data string, error
Write(data string) (int, error)

Writes data to the connection.

  • data: Text data to write
  • return: Number of bytes written, error
Close() error

Closes the connection.

GetLocalAddr() net.Addr

Returns the local network address.

GetRemoteAddr() net.Addr

Returns the remote network address.

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

Initializes and starts the socket server.

  • network: Network type ("tcp", "tcp4", "tcp6", "unix")
  • address: Listen address (e.g., ":8080", "127.0.0.1:8080")
  • clientPoolSize: Maximum number of concurrent connections to buffer
  • acceptSuccessFunc: Callback function for each connection
  • acceptFailureFunc: Callback function for Accept errors
Stop() error

Safely shuts down the socket server.

GetCondition() bool

Returns the server running status.

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

Notes

  • Client Read() and Write() must be used after calling Connect().
  • Server acceptSuccessFunc runs in a goroutine, so concurrency must be considered.
  • clientPoolSize determines the buffer size for connections that can be handled simultaneously.
  • When stopping the server, Stop() waits until all active connections are terminated.

License

This package follows the project's license.

Documentation

Overview

Package tcp provides TCP 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 socket client
  • Simple connect, read, write operations
  • Automatic connection management
  • Local and remote address access
  • Resource cleanup

Basic Client Example

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

Package tcp provides TCP 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 socket server
  • Concurrent client connection handling
  • Client connection pooling
  • Automatic resource cleanup
  • Custom accept success/failure handlers

Basic Server Example

server := &tcp.Server{}
err := server.Start("tcp", ":8080", 100,
    func(client tcp.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", "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", "unix")
  • address: Listen address (e.g., ":8080", "127.0.0.1:8080")
  • clientPoolSize: Channel buffer size for pending connections. This limits how many accepted connections can be queued before blocking the accept loop. Does not limit total concurrent connections.
  • acceptSuccessFunc: Callback for each accepted connection
  • acceptFailureFunc: Callback for accept errors (can be nil)

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