github.com/searKing/golang/go@v1.2.117/net/tcp/client.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package tcp 6 7 import ( 8 "context" 9 "net" 10 ) 11 12 type Client struct { 13 *Server 14 } 15 16 func NewClientFunc(onOpenHandler OnOpenHandler, 17 onMsgReadHandler OnMsgReadHandler, 18 onMsgHandleHandler OnMsgHandleHandler, 19 onCloseHandler OnCloseHandler, 20 onErrorHandler OnErrorHandler) *Client { 21 return &Client{ 22 Server: NewServerFunc(onOpenHandler, onMsgReadHandler, onMsgHandleHandler, onCloseHandler, onErrorHandler), 23 } 24 } 25 func NewClient(h Handler) *Client { 26 return NewClientFunc(h, h, h, h, h) 27 } 28 29 // Deprecated: use DialAndServe instead. 30 func (cli *Client) ListenAndServe() error { 31 return ErrUnImplement 32 } 33 34 func (cli *Client) DialAndServe(network, address string) error { 35 if cli.shuttingDown() { 36 return ErrClientClosed 37 } 38 // transfer http to websocket 39 conn, err := net.Dial(network, address) 40 if cli.Server.CheckError(nil, nil, err) != nil { 41 return err 42 } 43 44 defer conn.Close() 45 ctx := context.WithValue(context.Background(), ClientContextKey, cli) 46 47 // takeover the connect 48 c := cli.Server.newConn(conn) 49 // Handle websocket On 50 err = cli.Server.onOpenHandler.OnOpen(c.rwc) 51 if err = cli.Server.CheckError(c.rwc, c.rwc, err); err != nil { 52 c.close() 53 return err 54 } 55 c.setState(c.rwc, StateNew) // before Serve can return 56 57 c.serve(ctx) 58 return nil 59 }