conn

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2025 License: BSD-3-Clause Imports: 4 Imported by: 0

README

Conn Package

Go Reference License

A simple and efficient TCP connection data exchange utility for Go applications.

Features

  • Thread-safe, bidirectional data exchange between two TCP connections
  • Idle timeout support for automatic connection cleanup
  • Efficient error handling and resource management
  • TimeoutReader for per-read timeout control

Installation

go get github.com/NodePassProject/conn

Usage

TCP to TCP Data Exchange
package main

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

    "github.com/NodePassProject/conn"
)

func main() {
    // Example with two TCP connections
    conn1, err := net.Dial("tcp", "server1.example.com:8080")
    if err != nil {
        fmt.Printf("Failed to connect to server1: %v\n", err)
        return
    }
    defer conn1.Close()

    conn2, err := net.Dial("tcp", "server2.example.com:9090")
    if err != nil {
        fmt.Printf("Failed to connect to server2: %v\n", err)
        return
    }
    defer conn2.Close()

    // Exchange data between the two connections with a 5-second idle timeout
    bytesAtoB, bytesBtoA, err := conn.DataExchange(conn1, conn2, 5*time.Second)
    if err != nil && err != io.EOF {
        fmt.Printf("Data exchange error: %v\n", err)
    }

    fmt.Printf("Transferred %d bytes from server1 to server2\n", bytesAtoB)
    fmt.Printf("Transferred %d bytes from server2 to server1\n", bytesBtoA)
}
TimeoutReader

TimeoutReader is a wrapper for net.Conn that allows you to set a read timeout for each read operation. It is used internally by DataExchange, but can also be used directly if needed:

tr := &conn.TimeoutReader{Conn: tcpConn, timeout: 5 * time.Second}
buf := make([]byte, 4096)
n, err := tr.Read(buf)

License

Copyright (c) 2025, NodePassProject. Licensed under the BSD 3-Clause License. See the LICENSE file for details.

Documentation

Overview

Package conn 提供两条TCP连接之间双向数据交换功能

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DataExchange

func DataExchange(conn1, conn2 net.Conn, idleTimeout time.Duration) (int64, int64, error)

DataExchange 实现两个 net.Conn 之间的双向数据交换,支持空闲超时

Types

type TimeoutReader added in v1.0.2

type TimeoutReader struct {
	net.Conn
	// contains filtered or unexported fields
}

TimeoutReader 包装了 net.Conn,支持设置读取超时

func (*TimeoutReader) Read added in v1.0.2

func (tr *TimeoutReader) Read(b []byte) (int, error)

Read 实现了 io.Reader 接口,读取数据时会设置读取超时

Jump to

Keyboard shortcuts

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