Change tcpclient API

This commit is contained in:
qowevisa 2024-10-12 12:32:38 +03:00
parent 64e6494ff8
commit 45f08adff3
2 changed files with 17 additions and 7 deletions

View File

@ -1,14 +1,14 @@
package main package main
import ( import (
"fmt"
"time" "time"
"git.qowevisa.me/Qowevisa/tcpmachine/tcpclient" "git.qowevisa.me/Qowevisa/tcpmachine/tcpclient"
) )
func main() { func main() {
conf := tcpclient.GetDefaultConfig() client := tcpclient.CreateClient("127.0.0.1:10000")
client := tcpclient.CreateClient(conf)
go func() { go func() {
for { for {
if client.IsConnected { if client.IsConnected {
@ -21,6 +21,8 @@ func main() {
time.Sleep(time.Second) time.Sleep(time.Second)
} }
}() }()
go client.ErrorResolver(client.ErrorsChannel) err := client.StartClient()
client.StartClient("127.0.0.1:10000") if err != nil {
fmt.Printf("ERROR: StartClient: %v\n", err)
}
} }

View File

@ -23,6 +23,7 @@ func GetDefaultConfig() ClientConfiguration {
} }
type Client struct { type Client struct {
addr string
exit chan bool exit chan bool
Server net.Conn Server net.Conn
IsConnected bool IsConnected bool
@ -32,8 +33,15 @@ type Client struct {
ErrorResolver func(chan error) ErrorResolver func(chan error)
} }
func CreateClient(conf ClientConfiguration) *Client { func CreateClient(addr string, options ...ClientOption) *Client {
conf := GetDefaultConfig()
for _, opt := range options {
opt(conf)
}
return &Client{ return &Client{
addr: addr,
Messages: make(chan []byte, 16), Messages: make(chan []byte, 16),
ErrorResolver: conf.ErrorResolver, ErrorResolver: conf.ErrorResolver,
ErrorsChannel: make(chan error, 8), ErrorsChannel: make(chan error, 8),
@ -41,8 +49,8 @@ func CreateClient(conf ClientConfiguration) *Client {
} }
} }
func (c *Client) StartClient(addr string) error { func (c *Client) StartClient() error {
server, err := net.Dial("tcp", addr) server, err := net.Dial("tcp", c.addr)
if err != nil { if err != nil {
return fmt.Errorf("net.Dial: %w", err) return fmt.Errorf("net.Dial: %w", err)
} }