socket

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2021 License: MIT Imports: 17 Imported by: 25

README

socket

PkgGoDev Build Status codecov Go Report Card LICENSE

Package socket implements a network socket that supports TCP, UNIX, HTTP and WS.

Feature

Benchmark

Socket QPS
socket

Get started

Install
go get github.com/hslam/socket
Import
import "github.com/hslam/socket"
Usage
Example

server.go

package main

import (
	"flag"
	"github.com/hslam/socket"
)

var network string
var addr string

func init() {
	flag.StringVar(&network, "network", "tcp", "-network=tcp, unix, http or ws")
	flag.StringVar(&addr, "addr", ":8080", "-addr=:8080")
	flag.Parse()
}

func main() {
	sock, err := socket.NewSocket(network, nil)
	if err != nil {
		panic(err)
	}
	l, err := sock.Listen(addr)
	if err != nil {
		panic(err)
	}
	for {
		conn, err := l.Accept()
		if err != nil {
			panic(err)
		}
		go func(conn socket.Conn) {
			messages := conn.Messages()
			buf := make([]byte, 65536)
			for {
				msg, err := messages.ReadMessage(buf)
				if err != nil {
					break
				}
				messages.WriteMessage(msg)
			}
			messages.Close()
		}(conn)
	}
}

server_poll.go

package main

import (
	"flag"
	"github.com/hslam/socket"
	"sync"
)

var network string
var addr string

func init() {
	flag.StringVar(&network, "network", "tcp", "-network=tcp, unix, http or ws")
	flag.StringVar(&addr, "addr", ":8080", "-addr=:8080")
	flag.Parse()
}

func main() {
	sock, err := socket.NewSocket(network, nil)
	if err != nil {
		panic(err)
	}
	l, err := sock.Listen(addr)
	if err != nil {
		panic(err)
	}
	bufferPool := &sync.Pool{New: func() interface{} { return make([]byte, 65536) }}
	l.ServeMessages(func(messages socket.Messages) (socket.Context, error) {
		return messages, nil
	}, func(context socket.Context) error {
		messages := context.(socket.Messages)
		buf := bufferPool.Get().([]byte)
		defer bufferPool.Put(buf)
		msg, err := messages.ReadMessage(buf)
		if err != nil {
			return err
		}
		return messages.WriteMessage(msg)
	})
}

client.go

package main

import (
	"flag"
	"fmt"
	"github.com/hslam/socket"
)

var network string
var addr string

func init() {
	flag.StringVar(&network, "network", "tcp", "-network=tcp, unix, http or ws")
	flag.StringVar(&addr, "addr", ":8080", "-addr=:8080")
	flag.Parse()
}

func main() {
	sock, err := socket.NewSocket(network, nil)
	if err != nil {
		panic(err)
	}
	conn, err := sock.Dial(addr)
	if err != nil {
		panic(err)
	}
	messages := conn.Messages()
	buf := make([]byte, 65536)
	for i := 0; i < 1; i++ {
		err := messages.WriteMessage([]byte("Hello World"))
		if err != nil {
			panic(err)
		}
		msg, err := messages.ReadMessage(buf)
		if err != nil {
			panic(err)
		}
		fmt.Println(string(msg))
	}
}

Output

Hello World
License

This package is licensed under a MIT license (Copyright (c) 2020 Meng Huang)

Author

socket was written by Meng Huang.

Documentation

Overview

Package socket implements a network socket that supports TCP, UNIX, HTTP and WS.

Index

Constants

View Source
const (
	// HTTPConnected defines the http connected.
	HTTPConnected = "200 Connected to Server"
	// HTTPPath defines the http path.
	HTTPPath = "/"
)
View Source
const (
	//WSPath defines the ws path.
	WSPath = "/"
)

Variables

View Source
var DefaultCertPEM = []byte(`-----BEGIN CERTIFICATE-----
MIIDfDCCAmQCCQCAHkBfX03BnTANBgkqhkiG9w0BAQsFADB/MQswCQYDVQQGEwJD
TjELMAkGA1UECAwCQkoxEDAOBgNVBAcMB0JlaWppbmcxDjAMBgNVBAoMBUhTTEFN
MQwwCgYDVQQLDANSJkQxEjAQBgNVBAMMCWhzbGFtLmNvbTEfMB0GCSqGSIb3DQEJ
ARYQNzkxODc0MTU4QHFxLmNvbTAgFw0yMDA5MjMwMzE3NTdaGA8yMTIwMDgzMDAz
MTc1N1owfzELMAkGA1UEBhMCQ04xCzAJBgNVBAgMAkJKMRAwDgYDVQQHDAdCZWlq
aW5nMQ4wDAYDVQQKDAVIU0xBTTEMMAoGA1UECwwDUiZEMRIwEAYDVQQDDAloc2xh
bS5jb20xHzAdBgkqhkiG9w0BCQEWEDc5MTg3NDE1OEBxcS5jb20wggEiMA0GCSqG
SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa3lfVcQZg3Ra2DCeTPM9I8cv35Y+R4niX
J7c2U9TvGE3l8zfsLBXtdN4bSlmaimOnOmfx0aVJ8XwLqcIMspJmzG9UlGdlOfir
MTYCybvwhEf9bZc9lmLv27C4++4IljNF9sSv/Lnbdl5VNr+lY1xKRR3HPpwwuJj3
jh3TznzAnb0QnIRTyGGVThyE6uUQAgx8/taGenJDkzb7pry4kRvz+GgjAvhi/KOg
xho7G6PLfzXeS+iPyaMg5npd3B90XIzaaXr4/yffC5BUbynHhZLmWKJXSp7brjiZ
zpFV8np7wKYrtqXW4My2MtMASnvfXrCfTwQ3FU0biBsk7dQHCcuzAgMBAAEwDQYJ
KoZIhvcNAQELBQADggEBAA4rrtWczvjVpttxJ7pbXQlmvVrakPwqqKEQ09hxcoqY
EKkCucjJwFFQi1fNQBKpb+3BwlHIcfqdwpURiTwQjPmRgVhqdFqHE5pNF9EXdNm7
zaylUiu+ySKKHHnCVagM7UszovCoRYY3hq75UsGwR+9WWxOoWRz43NdOTBBDE9y7
JkRowySk9JE5isec+G0tDf6Fyj/3zWshWQalEH/Aq1Af0BMtWQL4VYXbealqK6rq
MOwPd7m67gCJlNREX2JnMDBM2A9QcAIzhYrHBx5w6UhUwSL6IFhJzdFXl4klsKUQ
cmw7rbPxsuPIyPlCobdtFoVpFN5vnOnF42nCb8tr0Xs=
-----END CERTIFICATE-----
`)

DefaultCertPEM represents the default certificate data.

View Source
var DefaultKeyPEM = []byte(`-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDa3lfVcQZg3Ra2
DCeTPM9I8cv35Y+R4niXJ7c2U9TvGE3l8zfsLBXtdN4bSlmaimOnOmfx0aVJ8XwL
qcIMspJmzG9UlGdlOfirMTYCybvwhEf9bZc9lmLv27C4++4IljNF9sSv/Lnbdl5V
Nr+lY1xKRR3HPpwwuJj3jh3TznzAnb0QnIRTyGGVThyE6uUQAgx8/taGenJDkzb7
pry4kRv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qfunjoOykdcqke
dKkVs4j/uzdFg49Ftmb4OfvRH73oMSsh3EyYResBvJG09qnoWhpNFpo7atLwlcWm
g6H5Eov0H6SDBaFzLFT5gty8sOSd6I3wbU0p5zkCgYAwQe8+M7Su2v3mA0vbxbGb
W96El5n15YRa6JHOigC+5mBhXilnDE8qomFkfELDOnQ+hdkgqbFd7P1/+K5raV+I
aGh+dZd2MKnLevVoMexu40NQLVyJTOqumG05NNgmfg7VE8QUbXKfz+9pmfYFSZGS
Wx4EqMDhdG9wlTsHGb1I/Q==
-----END PRIVATE KEY-----
`)

DefaultKeyPEM represents the default private key data.

View Source
var ErrConn = errors.New("conn is nil")

ErrConn is the error when the conn is nil

View Source
var ErrHandler = errors.New("handler is nil")

ErrHandler is the error when the handler is nil

View Source
var ErrNetwork = errors.New("network is not supported")

ErrNetwork is the error when the network is not supported

View Source
var ErrOpened = errors.New("opened is nil")

ErrOpened is the error when the opened is nil

View Source
var ErrServe = errors.New("serve is nil")

ErrServe is the error when the serve is nil

Functions

func Address

func Address(s Socket, url string) (string, error)

Address returns the socket's address by a url.

func DefalutTLSConfig

func DefalutTLSConfig() *tls.Config

DefalutTLSConfig returns a default TLS config.

func LoadTLSConfig

func LoadTLSConfig(certFile, keyFile string) (*tls.Config, error)

LoadTLSConfig returns a TLS config by loading the certificate file and the key file.

func SkipVerifyTLSConfig

func SkipVerifyTLSConfig() *tls.Config

SkipVerifyTLSConfig returns a insecure skip verify TLS config.

func TLSConfig

func TLSConfig(certPEM []byte, keyPEM []byte) *tls.Config

TLSConfig returns a TLS config by the certificate data and the key data.

func URL

func URL(s Socket, addr string) string

URL returns the socket's url by a address.

Types

type Batch

type Batch interface {
	// SetConcurrency sets a callback function concurrency to enable auto batch writer for improving throughput.
	SetConcurrency(concurrency func() int)
}

Batch interface is used to write batch messages.

type Conn

type Conn interface {
	net.Conn
	// Messages returns a new Messages.
	Messages() Messages
	// Connection returns the net.Conn.
	Connection() net.Conn
}

Conn is a generic stream-oriented network connection.

type Context

type Context interface{}

Context represents a context.

type Dialer

type Dialer interface {
	// Dial connects to an address.
	Dial(address string) (Conn, error)
}

Dialer is a generic network dialer for stream-oriented protocols.

type HTTP

type HTTP struct {
	Config *tls.Config
}

HTTP implements the Socket interface.

func (*HTTP) Dial

func (t *HTTP) Dial(address string) (Conn, error)

Dial connects to an address.

func (*HTTP) Listen

func (t *HTTP) Listen(address string) (Listener, error)

Listen announces on the local address.

func (*HTTP) Scheme

func (t *HTTP) Scheme() string

Scheme returns the socket's scheme.

type HTTPConn

type HTTPConn struct {
	net.Conn
}

HTTPConn implements the Conn interface.

func (*HTTPConn) Connection

func (c *HTTPConn) Connection() net.Conn

Connection returns the net.Conn.

func (*HTTPConn) Messages

func (c *HTTPConn) Messages() Messages

Messages returns a new Messages.

type HTTPListener

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

HTTPListener implements the Listener interface.

func (*HTTPListener) Accept

func (l *HTTPListener) Accept() (Conn, error)

Accept waits for and returns the next connection to the listener.

func (*HTTPListener) Addr

func (l *HTTPListener) Addr() net.Addr

Addr returns the listener's network address.

func (*HTTPListener) Close

func (l *HTTPListener) Close() error

Close closes the listener.

func (*HTTPListener) Serve

func (l *HTTPListener) Serve(handler netpoll.Handler) error

Serve serves the netpoll.Handler by the netpoll.

func (*HTTPListener) ServeConn

func (l *HTTPListener) ServeConn(opened func(net.Conn) (Context, error), serve func(Context) error) error

ServeConn serves the opened func and the serve func by the netpoll.

func (*HTTPListener) ServeData

func (l *HTTPListener) ServeData(opened func(net.Conn) error, serve func(req []byte) (res []byte)) error

ServeData serves the opened func and the serve func by the netpoll.

func (*HTTPListener) ServeMessages

func (l *HTTPListener) ServeMessages(opened func(Messages) (Context, error), serve func(Context) error) error

ServeMessages serves the opened func and the serve func by the netpoll.

type Listener

type Listener interface {
	// Accept waits for and returns the next connection to the listener.
	Accept() (Conn, error)
	// Close closes the listener.
	// Any blocked Accept operations will be unblocked and return errors.
	Close() error
	// Addr returns the listener's network address.
	Addr() net.Addr
	// Serve serves the netpoll.Handler by the netpoll.
	Serve(handler netpoll.Handler) error
	// ServeData serves the opened func and the serve func by the netpoll.
	ServeData(opened func(net.Conn) error, serve func(req []byte) (res []byte)) error
	// ServeConn serves the opened func and the serve func by the netpoll.
	ServeConn(opened func(net.Conn) (Context, error), serve func(Context) error) error
	// ServeMessages serves the opened func and the serve func by the netpoll.
	ServeMessages(opened func(Messages) (Context, error), serve func(Context) error) error
}

Listener is a generic network listener for stream-oriented protocols.

type Messages

type Messages interface {
	// ReadMessage reads single message frame from the Messages.
	ReadMessage(buf []byte) ([]byte, error)
	// WriteMessage writes data as a message frame to the Messages.
	WriteMessage([]byte) error
	// Close closes the Messages.
	Close() error
}

Messages interface is used to read and write message.

func NewMessages

func NewMessages(rwc io.ReadWriteCloser, shared bool, writeBufferSize int, readBufferSize int) Messages

NewMessages returns a new messages.

type Socket

type Socket interface {
	// Scheme returns the socket's scheme.
	Scheme() string
	Dialer
	// Listen announces on the local address.
	Listen(address string) (Listener, error)
}

Socket contains the Dialer and the Listener.

func NewHTTPSocket

func NewHTTPSocket(config *tls.Config) Socket

NewHTTPSocket returns a new HTTP socket.

func NewSocket

func NewSocket(network string, config *tls.Config) (Socket, error)

NewSocket returns a new socket by a network and a TLS config.

func NewTCPSocket

func NewTCPSocket(config *tls.Config) Socket

NewTCPSocket returns a new TCP socket.

func NewUNIXSocket

func NewUNIXSocket(config *tls.Config) Socket

NewUNIXSocket returns a new UNIX socket.

func NewWSSocket

func NewWSSocket(config *tls.Config) Socket

NewWSSocket returns a new WS socket.

type TCP

type TCP struct {
	Config *tls.Config
}

TCP implements the Socket interface.

func (*TCP) Dial

func (t *TCP) Dial(address string) (Conn, error)

Dial connects to an address.

func (*TCP) Listen

func (t *TCP) Listen(address string) (Listener, error)

Listen announces on the local address.

func (*TCP) Scheme

func (t *TCP) Scheme() string

Scheme returns the socket's scheme.

type TCPConn

type TCPConn struct {
	net.Conn
}

TCPConn implements the Conn interface.

func (*TCPConn) Connection

func (c *TCPConn) Connection() net.Conn

Connection returns the net.Conn.

func (*TCPConn) Messages

func (c *TCPConn) Messages() Messages

Messages returns a new Messages.

type TCPListener

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

TCPListener implements the Listener interface.

func (*TCPListener) Accept

func (l *TCPListener) Accept() (Conn, error)

Accept waits for and returns the next connection to the listener.

func (*TCPListener) Addr

func (l *TCPListener) Addr() net.Addr

Addr returns the listener's network address.

func (*TCPListener) Close

func (l *TCPListener) Close() error

Close closes the listener.

func (*TCPListener) Serve

func (l *TCPListener) Serve(handler netpoll.Handler) error

Serve serves the netpoll.Handler by the netpoll.

func (*TCPListener) ServeConn

func (l *TCPListener) ServeConn(opened func(net.Conn) (Context, error), serve func(Context) error) error

ServeConn serves the opened func and the serve func by the netpoll.

func (*TCPListener) ServeData

func (l *TCPListener) ServeData(opened func(net.Conn) error, serve func(req []byte) (res []byte)) error

ServeData serves the opened func and the serve func by the netpoll.

func (*TCPListener) ServeMessages

func (l *TCPListener) ServeMessages(opened func(Messages) (Context, error), serve func(Context) error) error

ServeMessages serves the opened func and the serve func by the netpoll.

type UNIX

type UNIX struct {
	Config *tls.Config
}

UNIX implements the Socket interface.

func (*UNIX) Dial

func (t *UNIX) Dial(address string) (Conn, error)

Dial connects to an address.

func (*UNIX) Listen

func (t *UNIX) Listen(address string) (Listener, error)

Listen announces on the local address.

func (*UNIX) Scheme

func (t *UNIX) Scheme() string

Scheme returns the socket's scheme.

type UNIXConn

type UNIXConn struct {
	net.Conn
}

UNIXConn implements the Conn interface.

func (*UNIXConn) Connection

func (c *UNIXConn) Connection() net.Conn

Connection returns the net.Conn.

func (*UNIXConn) Messages

func (c *UNIXConn) Messages() Messages

Messages returns a new Messages.

type UNIXListener

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

UNIXListener implements the Listener interface.

func (*UNIXListener) Accept

func (l *UNIXListener) Accept() (Conn, error)

Accept waits for and returns the next connection to the listener.

func (*UNIXListener) Addr

func (l *UNIXListener) Addr() net.Addr

Addr returns the listener's network address.

func (*UNIXListener) Close

func (l *UNIXListener) Close() error

Close closes the listener.

func (*UNIXListener) Serve

func (l *UNIXListener) Serve(handler netpoll.Handler) error

Serve serves the netpoll.Handler by the netpoll.

func (*UNIXListener) ServeConn

func (l *UNIXListener) ServeConn(opened func(net.Conn) (Context, error), serve func(Context) error) error

ServeConn serves the opened func and the serve func by the netpoll.

func (*UNIXListener) ServeData

func (l *UNIXListener) ServeData(opened func(net.Conn) error, serve func(req []byte) (res []byte)) error

ServeData serves the opened func and the serve func by the netpoll.

func (*UNIXListener) ServeMessages

func (l *UNIXListener) ServeMessages(opened func(Messages) (Context, error), serve func(Context) error) error

ServeMessages serves the opened func and the serve func by the netpoll.

type WS

type WS struct {
	Config *tls.Config
}

WS implements the Socket interface.

func (*WS) Dial

func (t *WS) Dial(address string) (Conn, error)

Dial connects to an address.

func (*WS) Listen

func (t *WS) Listen(address string) (Listener, error)

Listen announces on the local address.

func (*WS) Scheme

func (t *WS) Scheme() string

Scheme returns the socket's scheme.

type WSConn

type WSConn struct {
	*websocket.Conn
}

WSConn implements the Conn interface.

func (*WSConn) Connection

func (c *WSConn) Connection() net.Conn

Connection returns the net.Conn.

func (*WSConn) Messages

func (c *WSConn) Messages() Messages

Messages returns a new Messages.

type WSListener

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

WSListener implements the Listener interface.

func (*WSListener) Accept

func (l *WSListener) Accept() (Conn, error)

Accept waits for and returns the next connection to the listener.

func (*WSListener) Addr

func (l *WSListener) Addr() net.Addr

Addr returns the listener's network address.

func (*WSListener) Close

func (l *WSListener) Close() error

Close closes the listener.

func (*WSListener) Serve

func (l *WSListener) Serve(handler netpoll.Handler) error

Serve serves the netpoll.Handler by the netpoll.

func (*WSListener) ServeConn

func (l *WSListener) ServeConn(opened func(net.Conn) (Context, error), serve func(Context) error) error

ServeConn serves the opened func and the serve func by the netpoll.

func (*WSListener) ServeData

func (l *WSListener) ServeData(opened func(net.Conn) error, serve func(req []byte) (res []byte)) error

ServeData serves the opened func and the serve func by the netpoll.

func (*WSListener) ServeMessages

func (l *WSListener) ServeMessages(opened func(Messages) (Context, error), serve func(Context) error) error

ServeMessages serves the opened func and the serve func by the netpoll.\

Jump to

Keyboard shortcuts

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