Class SocketClient
- All Implemented Interfaces:
Proxy
GSocketClient is a lightweight high-level utility class for connecting to
a network host using a connection oriented socket type.
You create a GSocketClient object, set any options you want, and then
call a sync or async connect operation, which returns a
SocketConnection subclass on success.
The type of the SocketConnection object returned depends on the
type of the underlying socket that is in use. For instance, for a TCP/IP
connection it will be a TcpConnection.
As GSocketClient is a lightweight object, you don't need to cache it. You
can just create a new one any time you need one.
- Since:
- 2.22
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classSocketClient.Builder<B extends SocketClient.Builder<B>>Inner class implementing a builder pattern to construct a GObject with properties.static interfaceFunctional interface declaration of theEventCallbackcallback.static classNested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallback, GObject.ObjectClass -
Constructor Summary
ConstructorsConstructorDescriptionCreates a new SocketClient.SocketClient(MemorySegment address) Create a SocketClient proxy instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddApplicationProxy(String protocol) Enable proxy protocols to be handled by the application.protected SocketClientasParent()Returns this instance as if it were its parent type.static SocketClient.Builder<? extends SocketClient.Builder> builder()ASocketClient.Builderobject constructs aSocketClientwith the specified properties.connect(SocketConnectable connectable, @Nullable Cancellable cancellable) Tries to resolve theconnectableand make a network connection to it.voidconnectAsync(SocketConnectable connectable, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) This is the asynchronous version of g_socket_client_connect().connectFinish(AsyncResult result) Finishes an async connect operation.connectToHost(String hostAndPort, short defaultPort, @Nullable Cancellable cancellable) This is a helper function for g_socket_client_connect().voidconnectToHostAsync(String hostAndPort, short defaultPort, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) This is the asynchronous version of g_socket_client_connect_to_host().connectToHostFinish(AsyncResult result) Finishes an async connect operation.connectToService(String domain, String service, @Nullable Cancellable cancellable) Attempts to create a TCP connection to a service.voidconnectToServiceAsync(String domain, String service, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) This is the asynchronous version of g_socket_client_connect_to_service().connectToServiceFinish(AsyncResult result) Finishes an async connect operation.connectToUri(String uri, short defaultPort, @Nullable Cancellable cancellable) This is a helper function for g_socket_client_connect().voidconnectToUriAsync(String uri, short defaultPort, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) This is the asynchronous version of g_socket_client_connect_to_uri().connectToUriFinish(AsyncResult result) Finishes an async connect operation.voidemitEvent(SocketClientEvent event, @Nullable SocketConnectable connectable, @Nullable IOStream connection) Emits the "event" signal.protected voidevent(SocketClientEvent event, SocketConnectable connectable, IOStream connection) booleanGets the proxy enable state; see g_socket_client_set_enable_proxy()Gets the socket family of the socket client.@Nullable SocketAddressGets the local address of the socket client.static MemoryLayoutThe memory layout of the native struct.Gets the protocol name type of the socket client.Gets theGProxyResolverbeing used byclient.Normally, this will be the resolver returned by g_proxy_resolver_get_default(), but you can override it with g_socket_client_set_proxy_resolver().Gets the socket type of the socket client.intGets the I/O timeout time for sockets created byclient.booleangetTls()Gets whether this SocketClient creates TLS connections.Deprecated.Do not attempt to ignore validation errors.static @Nullable TypegetType()Get the GType of the SocketClient classonEvent(SocketClient.EventCallback handler) Emitted whenclient'sactivity onconnectablechanges state.voidsetEnableProxy(boolean enable) Sets whether or not this SocketClient attempts to make connections via a proxy server.voidsetFamily(SocketFamily family) Sets the socket family of the socket client.voidsetLocalAddress(@Nullable SocketAddress address) Sets the local address of the socket client.voidsetProtocol(SocketProtocol protocol) Sets the protocol of the socket client.voidsetProxyResolver(@Nullable ProxyResolver proxyResolver) Overrides theGProxyResolverused byclient.You can call this if you want to use specific proxies, rather than using the system default proxy settings.voidsetSocketType(SocketType type) Sets the socket type of the socket client.voidsetTimeout(int timeout) Sets the I/O timeout for sockets created byclient.timeoutis a time in seconds, or 0 for no timeout (the default).voidsetTls(boolean tls) Sets whether this SocketClient creates TLS (aka SSL) connections.voidDeprecated.Do not attempt to ignore validation errors.voidsetTlsValidationFlags(TlsCertificateFlags... flags) Deprecated.Do not attempt to ignore validation errors.Methods inherited from class org.gnome.gobject.GObject
addToggleRef, addWeakPointer, bindProperty, bindProperty, bindProperty, bindPropertyFull, bindPropertyFull, bindPropertyWithClosures, bindPropertyWithClosures, compatControl, connect, connect, connect, constructed, disconnect, dispatchPropertiesChanged, dispose, dupData, dupQdata, emit, emitNotify, finalize_, forceFloating, freezeNotify, get, getData, getProperty, getProperty, getProperty, getQdata, getv, interfaceFindProperty, interfaceInstallProperty, interfaceListProperties, isFloating, newInstance, newInstance, newv, notify, notify, notifyByPspec, onNotify, ref, refSink, removeToggleRef, removeWeakPointer, replaceData, replaceQdata, runDispose, set, setData, setDataFull, setProperty, setProperty, setProperty, setQdata, setQdataFull, setv, stealData, stealQdata, takeRef, thawNotify, unref, watchClosure, weakRef, weakUnref, withPropertiesMethods inherited from class org.gnome.gobject.TypeInstance
callParent, callParent, cast, getPrivate, readGClass, writeGClassMethods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCode
-
Constructor Details
-
SocketClient
Create a SocketClient proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
SocketClient
public SocketClient()Creates a new SocketClient.
-
-
Method Details
-
getType
-
getMemoryLayout
The memory layout of the native struct.- Returns:
- the memory layout
-
asParent
Returns this instance as if it were its parent type. This is mostly synonymous to the Javasuperkeyword, but will set the native typeclass function pointers to the parent type. When overriding a native virtual method in Java, "chaining up" withsuper.methodName()doesn't work, because it invokes the overridden function pointer again. To chain up, callasParent().methodName(). This will call the native function pointer of this virtual method in the typeclass of the parent type. -
addApplicationProxy
Enable proxy protocols to be handled by the application. When the indicated proxy protocol is returned by theGProxyResolver,GSocketClientwill consider this protocol as supported but will not try to find aGProxyinstance to handle handshaking. The application must check for this case by calling g_socket_connection_get_remote_address() on the returnedGSocketConnection, and seeing if it's aGProxyAddressof the appropriate type, to determine whether or not it needs to handle the proxy handshaking itself.This should be used for proxy protocols that are dialects of another protocol such as HTTP proxy. It also allows cohabitation of proxy protocols that are reused between protocols. A good example is HTTP. It can be used to proxy HTTP, FTP and Gopher and can also be use as generic socket proxy through the HTTP CONNECT method.
When the proxy is detected as being an application proxy, TLS handshake will be skipped. This is required to let the application do the proxy specific handshake.
- Parameters:
protocol- The proxy protocol
-
connect
public SocketConnection connect(SocketConnectable connectable, @Nullable Cancellable cancellable) throws GErrorException Tries to resolve theconnectableand make a network connection to it.Upon a successful connection, a new
GSocketConnectionis constructed and returned. The caller owns this new object and must drop their reference to it when finished with it.The type of the
GSocketConnectionobject returned depends on the type of the underlying socket that is used. For instance, for a TCP/IP connection it will be aGTcpConnection.The socket created will be the same family as the address that the
connectableresolves to, unless family is set with g_socket_client_set_family() or indirectly via g_socket_client_set_local_address(). The socket type defaults toSocketType.STREAMbut can be set with g_socket_client_set_socket_type().If a local address is specified with g_socket_client_set_local_address() the socket will be bound to this address before connecting.
- Parameters:
connectable- aGSocketConnectablespecifying the remote address.cancellable- optionalGCancellableobject,nullto ignore.- Returns:
- a
GSocketConnectionon success,nullon error. - Throws:
GErrorException- seeGError- Since:
- 2.22
-
connectAsync
public void connectAsync(SocketConnectable connectable, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) This is the asynchronous version of g_socket_client_connect().You may wish to prefer the asynchronous version even in synchronous command line programs because, since 2.60, it implements RFC 8305 "Happy Eyeballs" recommendations to work around long connection timeouts in networks where IPv6 is broken by performing an IPv4 connection simultaneously without waiting for IPv6 to time out, which is not supported by the synchronous call. (This is not an API guarantee, and may change in the future.)
When the operation is finished
callbackwill be called. You can then call g_socket_client_connect_finish() to get the result of the operation.- Parameters:
connectable- aGSocketConnectablespecifying the remote address.cancellable- aGCancellable, ornullcallback- aGAsyncReadyCallback- Since:
- 2.22
-
connectFinish
Finishes an async connect operation. See g_socket_client_connect_async()- Parameters:
result- aGAsyncResult.- Returns:
- a
GSocketConnectionon success,nullon error. - Throws:
GErrorException- seeGError- Since:
- 2.22
-
connectToHost
public SocketConnection connectToHost(String hostAndPort, short defaultPort, @Nullable Cancellable cancellable) throws GErrorException This is a helper function for g_socket_client_connect().Attempts to create a TCP connection to the named host.
hostAndPortmay be in any of a number of recognized formats; an IPv6 address, an IPv4 address, or a domain name (in which case a DNS lookup is performed). Quoting with [] is supported for all address types. A port override may be specified in the usual way with a colon. Ports may be given as decimal numbers or symbolic names (in which case an /etc/services lookup is performed).If no port override is given in
hostAndPortthendefaultPortwill be used as the port number to connect to.In general,
hostAndPortis expected to be provided by the user (allowing them to give the hostname, and a port override if necessary) anddefaultPortis expected to be provided by the application.In the case that an IP address is given, a single connection attempt is made. In the case that a name is given, multiple connection attempts may be made, in turn and according to the number of address records in DNS, until a connection succeeds.
Upon a successful connection, a new
GSocketConnectionis constructed and returned. The caller owns this new object and must drop their reference to it when finished with it.In the event of any failure (DNS error, service not found, no hosts connectable)
nullis returned anderror(if non-null) is set accordingly.- Parameters:
hostAndPort- the name and optionally port of the host to connect todefaultPort- the default port to connect tocancellable- aGCancellable, ornull- Returns:
- a
GSocketConnectionon success,nullon error. - Throws:
GErrorException- seeGError- Since:
- 2.22
-
connectToHostAsync
public void connectToHostAsync(String hostAndPort, short defaultPort, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) This is the asynchronous version of g_socket_client_connect_to_host().When the operation is finished
callbackwill be called. You can then call g_socket_client_connect_to_host_finish() to get the result of the operation.- Parameters:
hostAndPort- the name and optionally the port of the host to connect todefaultPort- the default port to connect tocancellable- aGCancellable, ornullcallback- aGAsyncReadyCallback- Since:
- 2.22
-
connectToHostFinish
Finishes an async connect operation. See g_socket_client_connect_to_host_async()- Parameters:
result- aGAsyncResult.- Returns:
- a
GSocketConnectionon success,nullon error. - Throws:
GErrorException- seeGError- Since:
- 2.22
-
connectToService
public SocketConnection connectToService(String domain, String service, @Nullable Cancellable cancellable) throws GErrorException Attempts to create a TCP connection to a service.This call looks up the SRV record for
serviceatdomainfor the "tcp" protocol. It then attempts to connect, in turn, to each of the hosts providing the service until either a connection succeeds or there are no hosts remaining.Upon a successful connection, a new
GSocketConnectionis constructed and returned. The caller owns this new object and must drop their reference to it when finished with it.In the event of any failure (DNS error, service not found, no hosts connectable)
nullis returned anderror(if non-null) is set accordingly.- Parameters:
domain- a domain nameservice- the name of the service to connect tocancellable- aGCancellable, ornull- Returns:
- a
GSocketConnectionif successful, ornullon error - Throws:
GErrorException- seeGError
-
connectToServiceAsync
public void connectToServiceAsync(String domain, String service, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) This is the asynchronous version of g_socket_client_connect_to_service().- Parameters:
domain- a domain nameservice- the name of the service to connect tocancellable- aGCancellable, ornullcallback- aGAsyncReadyCallback- Since:
- 2.22
-
connectToServiceFinish
Finishes an async connect operation. See g_socket_client_connect_to_service_async()- Parameters:
result- aGAsyncResult.- Returns:
- a
GSocketConnectionon success,nullon error. - Throws:
GErrorException- seeGError- Since:
- 2.22
-
connectToUri
public SocketConnection connectToUri(String uri, short defaultPort, @Nullable Cancellable cancellable) throws GErrorException This is a helper function for g_socket_client_connect().Attempts to create a TCP connection with a network URI.
urimay be any valid URI containing an "authority" (hostname/port) component. If a port is not specified in the URI,defaultPortwill be used. TLS will be negotiated ifGSocketClient:tls istrue. (GSocketClientdoes not know to automatically assume TLS for certain URI schemes.)Using this rather than g_socket_client_connect() or g_socket_client_connect_to_host() allows
GSocketClientto determine when to use application-specific proxy protocols.Upon a successful connection, a new
GSocketConnectionis constructed and returned. The caller owns this new object and must drop their reference to it when finished with it.In the event of any failure (DNS error, service not found, no hosts connectable)
nullis returned anderror(if non-null) is set accordingly.- Parameters:
uri- A network URIdefaultPort- the default port to connect tocancellable- aGCancellable, ornull- Returns:
- a
GSocketConnectionon success,nullon error. - Throws:
GErrorException- seeGError- Since:
- 2.26
-
connectToUriAsync
public void connectToUriAsync(String uri, short defaultPort, @Nullable Cancellable cancellable, @Nullable AsyncReadyCallback callback) This is the asynchronous version of g_socket_client_connect_to_uri().When the operation is finished
callbackwill be called. You can then call g_socket_client_connect_to_uri_finish() to get the result of the operation.- Parameters:
uri- a network uridefaultPort- the default port to connect tocancellable- aGCancellable, ornullcallback- aGAsyncReadyCallback- Since:
- 2.26
-
connectToUriFinish
Finishes an async connect operation. See g_socket_client_connect_to_uri_async()- Parameters:
result- aGAsyncResult.- Returns:
- a
GSocketConnectionon success,nullon error. - Throws:
GErrorException- seeGError- Since:
- 2.26
-
getEnableProxy
public boolean getEnableProxy()Gets the proxy enable state; see g_socket_client_set_enable_proxy()- Returns:
- whether proxying is enabled
- Since:
- 2.26
-
getFamily
Gets the socket family of the socket client.See g_socket_client_set_family() for details.
- Returns:
- a
GSocketFamily - Since:
- 2.22
-
getLocalAddress
Gets the local address of the socket client.See g_socket_client_set_local_address() for details.
- Returns:
- a
GSocketAddressornull. Do not free. - Since:
- 2.22
-
getProtocol
Gets the protocol name type of the socket client.See g_socket_client_set_protocol() for details.
- Returns:
- a
GSocketProtocol - Since:
- 2.22
-
getProxyResolver
Gets theGProxyResolverbeing used byclient.Normally, this will be the resolver returned by g_proxy_resolver_get_default(), but you can override it with g_socket_client_set_proxy_resolver().- Returns:
- The
GProxyResolverbeing used byclient. - Since:
- 2.36
-
getSocketType
Gets the socket type of the socket client.See g_socket_client_set_socket_type() for details.
- Returns:
- a
GSocketFamily - Since:
- 2.22
-
getTimeout
public int getTimeout()Gets the I/O timeout time for sockets created byclient.See g_socket_client_set_timeout() for details.
- Returns:
- the timeout in seconds
- Since:
- 2.26
-
getTls
public boolean getTls()Gets whether this SocketClient creates TLS connections. See g_socket_client_set_tls() for details.- Returns:
- whether this SocketClient uses TLS
- Since:
- 2.28
-
getTlsValidationFlags
Deprecated.Do not attempt to ignore validation errors.Gets the TLS validation flags used creating TLS connections viaclient.This function does not work as originally designed and is impossible to use correctly. See
GSocketClient:tls-validation-flags for more information.- Returns:
- the TLS validation flags
- Since:
- 2.28
-
setEnableProxy
public void setEnableProxy(boolean enable) Sets whether or not this SocketClient attempts to make connections via a proxy server. When enabled (the default),GSocketClientwill use aGProxyResolverto determine if a proxy protocol such as SOCKS is needed, and automatically do the necessary proxy negotiation.See also g_socket_client_set_proxy_resolver().
- Parameters:
enable- whether to enable proxies- Since:
- 2.26
-
setFamily
Sets the socket family of the socket client. If this is set to something other thanSocketFamily.INVALIDthen the sockets created by this object will be of the specified family.This might be useful for instance if you want to force the local connection to be an ipv4 socket, even though the address might be an ipv6 mapped to ipv4 address.
- Parameters:
family- aGSocketFamily- Since:
- 2.22
-
setLocalAddress
Sets the local address of the socket client. The sockets created by this object will bound to the specified address (if notnull) before connecting.This is useful if you want to ensure that the local side of the connection is on a specific port, or on a specific interface.
- Parameters:
address- aGSocketAddress, ornull- Since:
- 2.22
-
setProtocol
Sets the protocol of the socket client. The sockets created by this object will use of the specified protocol.If
protocolisSocketProtocol.DEFAULTthat means to use the default protocol for the socket family and type.- Parameters:
protocol- aGSocketProtocol- Since:
- 2.22
-
setProxyResolver
Overrides theGProxyResolverused byclient.You can call this if you want to use specific proxies, rather than using the system default proxy settings.Note that whether or not the proxy resolver is actually used depends on the setting of
GSocketClient:enable-proxy, which is not changed by this function (but which istrueby default)- Parameters:
proxyResolver- aGProxyResolver, ornullfor the default.- Since:
- 2.36
-
setSocketType
Sets the socket type of the socket client. The sockets created by this object will be of the specified type.It doesn't make sense to specify a type of
SocketType.DATAGRAM, as GSocketClient is used for connection oriented services.- Parameters:
type- aGSocketType- Since:
- 2.22
-
setTimeout
public void setTimeout(int timeout) Sets the I/O timeout for sockets created byclient.timeoutis a time in seconds, or 0 for no timeout (the default).The timeout value affects the initial connection attempt as well, so setting this may cause calls to g_socket_client_connect(), etc, to fail with
IOErrorEnum.TIMED_OUT.- Parameters:
timeout- the timeout- Since:
- 2.26
-
setTls
public void setTls(boolean tls) Sets whether this SocketClient creates TLS (aka SSL) connections. Iftlsistrue, this SocketClient will wrap its connections in aGTlsClientConnectionand perform a TLS handshake when connecting.Note that since
GSocketClientmust return aGSocketConnection, butGTlsClientConnectionis not aGSocketConnection, this actually wraps the resultingGTlsClientConnectionin aGTcpWrapperConnectionwhen returning it. You can use g_tcp_wrapper_connection_get_base_io_stream() on the return value to extract theGTlsClientConnection.If you need to modify the behavior of the TLS handshake (eg, by setting a client-side certificate to use, or connecting to the
GTlsConnection::accept-certificate signal), you can connect toclient'sGSocketClient::event signal and wait for it to be emitted withSocketClientEvent.TLS_HANDSHAKING, which will give you a chance to see theGTlsClientConnectionbefore the handshake starts.- Parameters:
tls- whether to use TLS- Since:
- 2.28
-
setTlsValidationFlags
Deprecated.Do not attempt to ignore validation errors.Sets the TLS validation flags used when creating TLS connections viaclient.The default value isTlsCertificateFlags.VALIDATE_ALL.This function does not work as originally designed and is impossible to use correctly. See
GSocketClient:tls-validation-flags for more information.- Parameters:
flags- the validation flags- Since:
- 2.28
-
setTlsValidationFlags
Deprecated.Do not attempt to ignore validation errors.Sets the TLS validation flags used when creating TLS connections viaclient.The default value isTlsCertificateFlags.VALIDATE_ALL.This function does not work as originally designed and is impossible to use correctly. See
GSocketClient:tls-validation-flags for more information.- Parameters:
flags- the validation flags- Since:
- 2.28
-
event
-
onEvent
Emitted whenclient'sactivity onconnectablechanges state. Among other things, this can be used to provide progress information about a network connection in the UI. The meanings of the differenteventvalues are as follows:SocketClientEvent.RESOLVING:clientis about to look upconnectablein DNS.connectionwill benull.
SocketClientEvent.RESOLVED:clienthas successfully resolvedconnectablein DNS.connectionwill benull.
SocketClientEvent.CONNECTING:clientis about to make a connection to a remote host; either a proxy server or the destination server itself.connectionis theGSocketConnection, which is not yet connected. Since GLib 2.40, you can access the remote address via g_socket_connection_get_remote_address().
SocketClientEvent.CONNECTED:clienthas successfully connected to a remote host.connectionis the connectedGSocketConnection.
SocketClientEvent.PROXY_NEGOTIATING:clientis about to negotiate with a proxy to get it to connect toconnectable.connectionis theGSocketConnectionto the proxy server.
SocketClientEvent.PROXY_NEGOTIATED:clienthas negotiated a connection toconnectablethrough a proxy server.connectionis the stream returned from g_proxy_connect(), which may or may not be aGSocketConnection.
SocketClientEvent.TLS_HANDSHAKING:clientis about to begin a TLS handshake.connectionis aGTlsClientConnection.
SocketClientEvent.TLS_HANDSHAKED:clienthas successfully completed the TLS handshake.connectionis aGTlsClientConnection.
SocketClientEvent.COMPLETE:clienthas either successfully connected toconnectable(in which caseconnectionis theGSocketConnectionthat it will be returning to the caller) or has failed (in which caseconnectionisnulland the client is about to return an error).
Each event except
SocketClientEvent.COMPLETEmay be emitted multiple times (or not at all) for a given connectable (in particular, ifclientends up attempting to connect to more than one address). However, ifclientemits theGSocketClient::event signal at all for a given connectable, then it will always emit it withSocketClientEvent.COMPLETEwhen it is done.Note that there may be additional
GSocketClientEventvalues in the future; unrecognizedeventvalues should be ignored.- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- Since:
- 2.32
- See Also:
-
emitEvent
public void emitEvent(SocketClientEvent event, @Nullable SocketConnectable connectable, @Nullable IOStream connection) Emits the "event" signal. SeeonEvent(org.gnome.gio.SocketClient.EventCallback). -
builder
ASocketClient.Builderobject constructs aSocketClientwith the specified properties. Use the variousset...()methods to set properties, and finish construction withSocketClient.Builder.build().- Returns:
- the builder object
-