1414
1515use Spiral \Goridge \Exceptions \GoridgeException ;
1616use Spiral \Goridge \Exceptions \InvalidArgumentException ;
17+ use Spiral \Goridge \Exceptions \RelayException ;
1718use Swoole \Coroutine \Socket ;
1819
1920/**
@@ -87,6 +88,15 @@ public function __construct(string $address, int $port = null, int $type = self:
8788 $ this ->type = $ type ;
8889 }
8990
91+ public function __toString (): string
92+ {
93+ if ($ this ->type == self ::SOCK_TCP ) {
94+ return "tcp:// {$ this ->address }: {$ this ->port }" ;
95+ }
96+
97+ return "unix:// {$ this ->address }" ;
98+ }
99+
90100 /**
91101 * @return string
92102 */
@@ -111,6 +121,33 @@ public function getType(): int
111121 return $ this ->type ;
112122 }
113123
124+
125+ /**
126+ * Ensure socket connection. Returns true if socket successfully connected
127+ * or have already been connected.
128+ *
129+ * @throws RelayException
130+ * @throws \Error when sockets are used in unsupported environment
131+ */
132+ public function connect (): bool
133+ {
134+ if ($ this ->isConnected ()) {
135+ return true ;
136+ }
137+
138+ $ this ->socket = $ this ->createSocket ();
139+ try {
140+ // Port type needs to be int, so we convert null to 0
141+ if ($ this ->socket ->connect ($ this ->address , $ this ->port ?? 0 ) === false ) {
142+ throw new RelayException (sprintf ('%s (%s) ' , $ this ->socket ->errMsg , $ this ->socket ->errCode ));
143+ }
144+ } catch (\Exception $ e ) {
145+ throw new RelayException ("unable to establish connection {$ this }" , 0 , $ e );
146+ }
147+
148+ return true ;
149+ }
150+
114151 /**
115152 * @throws GoridgeException
116153 * @return Socket
0 commit comments