Class Socket
- All Implemented Interfaces:
DatagramBased,Initable,Proxy
GSocket is a low-level networking primitive. It is a more or less
direct mapping of the BSD socket API in a portable GObject based API.
It supports both the UNIX socket implementations and winsock2 on Windows.
GSocket is the platform independent base upon which the higher level
network primitives are based. Applications are not typically meant to
use it directly, but rather through classes like SocketClient,
SocketService and SocketConnection. However there may
be cases where direct use of GSocket is useful.
GSocket implements the Initable interface, so if it is manually
constructed by e.g. GObject() you must call
Initable.init(org.gnome.gio.Cancellable) and check the results before using the object.
This is done automatically in Socket() and
fromFd(int), so these functions can return NULL.
Sockets operate in two general modes, blocking or non-blocking. When
in blocking mode all operations (which don’t take an explicit blocking
parameter) block until the requested operation
is finished or there is an error. In non-blocking mode all calls that
would block return immediately with a G_IO_ERROR_WOULD_BLOCK error.
To know when a call would successfully run you can call
conditionCheck(java.util.Set<org.gnome.glib.IOCondition>), or conditionWait(java.util.Set<org.gnome.glib.IOCondition>, org.gnome.gio.Cancellable).
You can also use createSource(java.util.Set<org.gnome.glib.IOCondition>, org.gnome.gio.Cancellable) and attach it to a
GLib.MainContext to get callbacks when I/O is possible.
Note that all sockets are always set to non blocking mode in the system, and
blocking mode is emulated in GSocket.
When working in non-blocking mode applications should always be able to
handle getting a G_IO_ERROR_WOULD_BLOCK error even when some other
function said that I/O was possible. This can easily happen in case
of a race condition in the application, but it can also happen for other
reasons. For instance, on Windows a socket is always seen as writable
until a write returns G_IO_ERROR_WOULD_BLOCK.
GSockets can be either connection oriented or datagram based.
For connection oriented types you must first establish a connection by
either connecting to an address or accepting a connection from another
address. For connectionless socket types the target/source address is
specified or received in each I/O operation.
All socket file descriptors are set to be close-on-exec.
Note that creating a GSocket causes the signal SIGPIPE to be
ignored for the remainder of the program. If you are writing a
command-line utility that uses GSocket, you may need to take into
account the fact that your program will not automatically be killed
if it tries to write to stdout after it has been closed.
Like most other APIs in GLib, GSocket is not inherently thread safe. To use
a GSocket concurrently from multiple threads, you must implement your own
locking.
Nagle’s algorithm
Since GLib 2.80, GSocket will automatically set the TCP_NODELAY option on
all G_SOCKET_TYPE_STREAM sockets. This disables
Nagle’s algorithm as it
typically does more harm than good on modern networks.
If your application needs Nagle’s algorithm enabled, call
setOption(int, int, int) after constructing a GSocket to enable it:
socket = g_socket_new (…, G_SOCKET_TYPE_STREAM, …);
if (socket != NULL)
{
g_socket_set_option (socket, IPPROTO_TCP, TCP_NODELAY, FALSE, &local_error);
// handle error if needed
}
- Since:
- 2.22
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classSocket.Builder<B extends Socket.Builder<B>>Inner class implementing a builder pattern to construct a GObject with properties.static classNested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallback, GObject.ObjectClassNested classes/interfaces inherited from interface org.gnome.gio.DatagramBased
DatagramBased.DatagramBased$Impl, DatagramBased.DatagramBasedInterfaceNested classes/interfaces inherited from interface org.gnome.gio.Initable
Initable.Initable$Impl, Initable.InitableIface -
Constructor Summary
ConstructorsConstructorDescriptionSocket()Creates a new Socket.Socket(MemorySegment address) Create a Socket proxy instance for the provided memory address.Socket(SocketFamily family, SocketType type, SocketProtocol protocol) Creates a newGSocketwith the defined family, type and protocol. -
Method Summary
Modifier and TypeMethodDescriptionaccept(@Nullable Cancellable cancellable) Accept incoming connections on a connection-based socket.protected SocketasParent()Returns this instance as if it were its parent type.booleanbind(SocketAddress address, boolean allowReuse) When a socket is created it is attached to an address family, but it doesn't have an address in this family.static Socket.Builder<? extends Socket.Builder> builder()ASocket.Builderobject constructs aSocketwith the specified properties.booleanChecks and resets the pending connect error for the socket.booleanclose()Closes the socket, shutting down any active connection.conditionCheck(Set<IOCondition> condition) Checks on the readiness of this Socket to perform operations.conditionCheck(IOCondition... condition) Checks on the readiness of this Socket to perform operations.booleanconditionTimedWait(Set<IOCondition> condition, long timeoutUs, @Nullable Cancellable cancellable) Waits for up totimeoutUsmicroseconds forconditionto become true onsocket.If the condition is met,trueis returned.booleanconditionTimedWait(IOCondition condition, long timeoutUs, @Nullable Cancellable cancellable) Waits for up totimeoutUsmicroseconds forconditionto become true onsocket.If the condition is met,trueis returned.booleanconditionWait(Set<IOCondition> condition, @Nullable Cancellable cancellable) Waits forconditionto become true onsocket.When the condition is met,trueis returned.booleanconditionWait(IOCondition condition, @Nullable Cancellable cancellable) Waits forconditionto become true onsocket.When the condition is met,trueis returned.booleanconnect(SocketAddress address, @Nullable Cancellable cancellable) Connect the socket to the specified remote address.Creates aGSocketConnectionsubclass of the right type forsocket.createSource(Set<IOCondition> condition, @Nullable Cancellable cancellable) Creates aGSourcethat can be attached to aGMainContextto monitor for the availability of the specifiedconditionon the socket.createSource(IOCondition condition, @Nullable Cancellable cancellable) Creates aGSourcethat can be attached to aGMainContextto monitor for the availability of the specifiedconditionon the socket.static SocketfromFd(int fd) Creates a newGSocketfrom a native file descriptor or winsock SOCKET handle.longGet the amount of data pending in the OS input buffer, without blocking.booleanGets the blocking mode of the socket.booleanGets the broadcast setting onsocket;iftrue, it is possible to send packets to broadcast addresses.Returns the credentials of the foreign process connected to this socket, if any (e.g.Gets the socket family of the socket.intgetFd()Returns the underlying OS socket object.booleanGets the keepalive mode of the socket.intGets the listen backlog setting of the socket.Try to get the local address of a bound socket.static MemoryLayoutThe memory layout of the native struct.booleanGets the multicast loopback setting onsocket;iftrue(the default), outgoing multicast packets will be looped back to multicast listeners on the same host.intGets the multicast time-to-live setting onsocket;see g_socket_set_multicast_ttl() for more details.booleanGets the value of an integer-valued option onsocket,as with getsockopt().Gets the socket protocol id the socket was created with.Try to get the remote address of a connected socket.Gets the socket type of the socket.intGets the timeout setting of the socket.intgetTtl()Gets the unicast time-to-live setting onsocket;see g_socket_set_ttl() for more details.static @Nullable TypegetType()Get the GType of the Socket classbooleanisClosed()Checks whether a socket is closed.booleanCheck whether the socket is connected.booleanjoinMulticastGroup(InetAddress group, boolean sourceSpecific, @Nullable String iface) Registers this Socket to receive multicast messages sent togroup.this Socket must be aSocketType.DATAGRAMsocket, and must have been bound to an appropriate interface and port with g_socket_bind().booleanjoinMulticastGroupSsm(InetAddress group, @Nullable InetAddress sourceSpecific, @Nullable String iface) Registers this Socket to receive multicast messages sent togroup.this Socket must be aSocketType.DATAGRAMsocket, and must have been bound to an appropriate interface and port with g_socket_bind().booleanleaveMulticastGroup(InetAddress group, boolean sourceSpecific, @Nullable String iface) Removes this Socket from the multicast group defined bygroup,iface,andsourceSpecific(which must all have the same values they had when you joined the group).booleanleaveMulticastGroupSsm(InetAddress group, @Nullable InetAddress sourceSpecific, @Nullable String iface) Removes this Socket from the multicast group defined bygroup,iface,andsourceSpecific(which must all have the same values they had when you joined the group).booleanlisten()Marks the socket as a server socket, i.e.longreceive(@Nullable Out<byte[]> buffer, @Nullable Cancellable cancellable) Receive data (up tosizebytes) from a socket.byte[]receiveBytes(long size, long timeoutUs, @Nullable Cancellable cancellable) Receives data (up tosizebytes) from a socket.byte[]receiveBytesFrom(@Nullable Out<SocketAddress> address, long size, long timeoutUs, @Nullable Cancellable cancellable) Receive data (up tosizebytes) from a socket.longreceiveFrom(@Nullable Out<SocketAddress> address, @Nullable Out<byte[]> buffer, @Nullable Cancellable cancellable) Receive data (up tosizebytes) from a socket.longreceiveMessage(@Nullable Out<SocketAddress> address, @Nullable InputVector @Nullable [] vectors, @Nullable Out<SocketControlMessage[]> messages, Out<Integer> flags, @Nullable Cancellable cancellable) Receive data from a socket.intreceiveMessages(@Nullable InputMessage @Nullable [] messages, int flags, @Nullable Cancellable cancellable) Receive multiple data messages from this Socket in one go.longreceiveWithBlocking(@Nullable Out<byte[]> buffer, boolean blocking, @Nullable Cancellable cancellable) This behaves exactly the same as g_socket_receive(), except that the choice of blocking or non-blocking behavior is determined by theblockingargument rather than bysocket'sproperties.longsend(@org.jspecify.annotations.Nullable byte @Nullable [] buffer, @Nullable Cancellable cancellable) Tries to sendsizebytes frombufferon the socket.longsendMessage(@Nullable SocketAddress address, @Nullable OutputVector @Nullable [] vectors, @Nullable SocketControlMessage @Nullable [] messages, int flags, @Nullable Cancellable cancellable) Send data toaddressonsocket.For sending multiple messages see g_socket_send_messages(); for easier use, see g_socket_send() and g_socket_send_to().intsendMessages(@Nullable OutputMessage @Nullable [] messages, int flags, @Nullable Cancellable cancellable) Send multiple data messages from this Socket in one go.sendMessageWithTimeout(@Nullable SocketAddress address, @Nullable OutputVector @Nullable [] vectors, @Nullable SocketControlMessage @Nullable [] messages, int flags, long timeoutUs, @Nullable Out<Long> bytesWritten, @Nullable Cancellable cancellable) This behaves exactly the same as g_socket_send_message(), except that the choice of timeout behavior is determined by thetimeoutUsargument rather than bysocket'sproperties.longsendTo(@Nullable SocketAddress address, @org.jspecify.annotations.Nullable byte @Nullable [] buffer, @Nullable Cancellable cancellable) Tries to sendsizebytes frombuffertoaddress.Ifaddressisnullthen the message is sent to the default receiver (set by g_socket_connect()).longsendWithBlocking(@org.jspecify.annotations.Nullable byte @Nullable [] buffer, boolean blocking, @Nullable Cancellable cancellable) This behaves exactly the same as g_socket_send(), except that the choice of blocking or non-blocking behavior is determined by theblockingargument rather than bysocket'sproperties.voidsetBlocking(boolean blocking) Sets the blocking mode of the socket.voidsetBroadcast(boolean broadcast) Sets whether this Socket should allow sending to broadcast addresses.voidsetKeepalive(boolean keepalive) Sets or unsets theSO_KEEPALIVEflag on the underlying socket.voidsetListenBacklog(int backlog) Sets the maximum number of outstanding connections allowed when listening on this socket.voidsetMulticastLoopback(boolean loopback) Sets whether outgoing multicast packets will be received by sockets listening on that multicast address on the same host.voidsetMulticastTtl(int ttl) Sets the time-to-live for outgoing multicast datagrams onsocket.By default, this is 1, meaning that multicast packets will not leave the local network.booleansetOption(int level, int optname, int value) Sets the value of an integer-valued option onsocket,as with setsockopt().voidsetTimeout(int timeout) Sets the time in seconds after which I/O operations on this Socket will time out if they have not yet completed.voidsetTtl(int ttl) Sets the time-to-live for outgoing unicast packets onsocket.By default the platform-specific default value is used.booleanshutdown(boolean shutdownRead, boolean shutdownWrite) Shut down part or all of a full-duplex connection.booleanChecks if a socket is capable of speaking IPv4.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, hashCodeMethods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.gnome.gio.DatagramBased
conditionWait, conditionWait, receiveMessages, sendMessages
-
Constructor Details
-
Socket
Create a Socket proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
Socket
Creates a newGSocketwith the defined family, type and protocol. Ifprotocolis 0 (SocketProtocol.DEFAULT) the default protocol type for the family and type is used.The
protocolis a family and type specific int that specifies what kind of protocol to use.GSocketProtocollists several common ones. Many families only support one protocol, and use 0 for this, others support several and using 0 means to use the default protocol for the family and type.The protocol id is passed directly to the operating system, so you can use protocols not listed in
GSocketProtocolif you know the protocol number used for it.- Parameters:
family- the socket family to use, e.g.SocketFamily.IPV4.type- the socket type to use.protocol- the id of the protocol to use, or 0 for default.- Throws:
GErrorException- seeGError- Since:
- 2.22
-
Socket
public Socket()Creates a new Socket.
-
-
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. -
fromFd
Creates a newGSocketfrom a native file descriptor or winsock SOCKET handle.This reads all the settings from the file descriptor so that all properties should work. Note that the file descriptor will be set to non-blocking mode, independent on the blocking mode of the
GSocket.On success, the returned
GSockettakes ownership offd.On failure, the caller must closefdthemselves.Since GLib 2.46, it is no longer a fatal error to call this on a non-socket descriptor. Instead, a GError will be set with code
IOErrorEnum.FAILED- Parameters:
fd- a native socket file descriptor.- Returns:
- a
GSocketornullon error. Free the returned object with g_object_unref(). - Throws:
GErrorException- seeGError- Since:
- 2.22
-
accept
Accept incoming connections on a connection-based socket. This removes the first outstanding connection request from the listening socket and creates aGSocketobject for it.The this Socket must be bound to a local address with g_socket_bind() and must be listening for incoming connections (g_socket_listen()).
If there are no outstanding connections then the operation will block or return
IOErrorEnum.WOULD_BLOCKif non-blocking I/O is enabled. To be notified of an incoming connection, wait for theIOCondition.INcondition.- Parameters:
cancellable- aGCancellableornull- Returns:
- a new
GSocket, ornullon error. Free the returned object with g_object_unref(). - Throws:
GErrorException- seeGError- Since:
- 2.22
-
bind
When a socket is created it is attached to an address family, but it doesn't have an address in this family. g_socket_bind() assigns the address (sometimes called name) of the socket.It is generally required to bind to a local address before you can receive connections. (See g_socket_listen() and g_socket_accept() ). In certain situations, you may also want to bind a socket that will be used to initiate connections, though this is not normally required.
If this Socket is a TCP socket, then
allowReusecontrols the setting of theSO_REUSEADDRsocket option; normally it should betruefor server sockets (sockets that you will eventually call g_socket_accept() on), andfalsefor client sockets. (Failing to set this flag on a server socket may cause g_socket_bind() to returnIOErrorEnum.ADDRESS_IN_USEif the server program is stopped and then immediately restarted.)If this Socket is a UDP socket, then
allowReusedetermines whether or not other UDP sockets can be bound to the same address at the same time. In particular, you can have several UDP sockets bound to the same address, and they will all receive all of the multicast and broadcast packets sent to that address. (The behavior of unicast UDP packets to an address with multiple listeners is not defined.)- Parameters:
address- aGSocketAddressspecifying the local address.allowReuse- whether to allow reusing this address- Returns:
trueon success,falseon error.- Throws:
GErrorException- seeGError- Since:
- 2.22
-
checkConnectResult
Checks and resets the pending connect error for the socket. This is used to check for errors when g_socket_connect() is used in non-blocking mode.- Returns:
trueif no error,falseotherwise, settingerrorto the error- Throws:
GErrorException- seeGError- Since:
- 2.22
-
close
Closes the socket, shutting down any active connection.Closing a socket does not wait for all outstanding I/O operations to finish, so the caller should not rely on them to be guaranteed to complete even if the close returns with no error.
Once the socket is closed, all other operations will return
IOErrorEnum.CLOSED. Closing a socket multiple times will not return an error.Sockets will be automatically closed when the last reference is dropped, but you might want to call this function to make sure resources are released as early as possible.
Beware that due to the way that TCP works, it is possible for recently-sent data to be lost if either you close a socket while the
IOCondition.INcondition is set, or else if the remote connection tries to send something to you after you close the socket but before it has finished reading all of the data you sent. There is no easy generic way to avoid this problem; the easiest fix is to design the network protocol such that the client will never send data "out of turn". Another solution is for the server to half-close the connection by calling g_socket_shutdown() with only theshutdownWriteflag set, and then wait for the client to notice this and close its side of the connection, after which the server can safely call g_socket_close(). (This is whatGTcpConnectiondoes if you call g_tcp_connection_set_graceful_disconnect(). But of course, this only works if the client will close its connection after the server does.)- Returns:
trueon success,falseon error- Throws:
GErrorException- seeGError- Since:
- 2.22
-
conditionCheck
Checks on the readiness of this Socket to perform operations. The operations specified inconditionare checked for and masked against the currently-satisfied conditions onsocket.The result is returned.Note that on Windows, it is possible for an operation to return
IOErrorEnum.WOULD_BLOCKeven immediately after g_socket_condition_check() has claimed that the socket is ready for writing. Rather than calling g_socket_condition_check() and then writing to the socket if it succeeds, it is generally better to simply try writing to the socket right away, and try again later if the initial attempt returnsIOErrorEnum.WOULD_BLOCK.It is meaningless to specify
IOCondition.ERRorIOCondition.HUPin condition; these conditions will always be set in the output if they are true.This call never blocks.
- Specified by:
conditionCheckin interfaceDatagramBased- Parameters:
condition- aGIOConditionmask to check- Returns:
- the
GIOConditionmask of the current state - Since:
- 2.22
-
conditionCheck
Checks on the readiness of this Socket to perform operations. The operations specified inconditionare checked for and masked against the currently-satisfied conditions onsocket.The result is returned.Note that on Windows, it is possible for an operation to return
IOErrorEnum.WOULD_BLOCKeven immediately after g_socket_condition_check() has claimed that the socket is ready for writing. Rather than calling g_socket_condition_check() and then writing to the socket if it succeeds, it is generally better to simply try writing to the socket right away, and try again later if the initial attempt returnsIOErrorEnum.WOULD_BLOCK.It is meaningless to specify
IOCondition.ERRorIOCondition.HUPin condition; these conditions will always be set in the output if they are true.This call never blocks.
- Specified by:
conditionCheckin interfaceDatagramBased- Parameters:
condition- aGIOConditionmask to check- Returns:
- the
GIOConditionmask of the current state - Since:
- 2.22
-
conditionTimedWait
public boolean conditionTimedWait(Set<IOCondition> condition, long timeoutUs, @Nullable Cancellable cancellable) throws GErrorException Waits for up totimeoutUsmicroseconds forconditionto become true onsocket.If the condition is met,trueis returned.If
cancellableis cancelled before the condition is met, or iftimeoutUs(or the socket'sGSocket:timeout) is reached before the condition is met, thenfalseis returned anderror,if non-null, is set to the appropriate value (IOErrorEnum.CANCELLEDorIOErrorEnum.TIMED_OUT).If you don't want a timeout, use g_socket_condition_wait(). (Alternatively, you can pass -1 for
timeoutUs.)Note that although
timeoutUsis in microseconds for consistency with other GLib APIs, this function actually only has millisecond resolution, and the behavior is undefined iftimeoutUsis not an exact number of milliseconds.- Parameters:
condition- aGIOConditionmask to wait fortimeoutUs- the maximum time (in microseconds) to wait, or -1cancellable- aGCancellable, ornull- Returns:
trueif the condition was met,falseotherwise- Throws:
GErrorException- seeGError- Since:
- 2.32
-
conditionTimedWait
public boolean conditionTimedWait(IOCondition condition, long timeoutUs, @Nullable Cancellable cancellable) throws GErrorException Waits for up totimeoutUsmicroseconds forconditionto become true onsocket.If the condition is met,trueis returned.If
cancellableis cancelled before the condition is met, or iftimeoutUs(or the socket'sGSocket:timeout) is reached before the condition is met, thenfalseis returned anderror,if non-null, is set to the appropriate value (IOErrorEnum.CANCELLEDorIOErrorEnum.TIMED_OUT).If you don't want a timeout, use g_socket_condition_wait(). (Alternatively, you can pass -1 for
timeoutUs.)Note that although
timeoutUsis in microseconds for consistency with other GLib APIs, this function actually only has millisecond resolution, and the behavior is undefined iftimeoutUsis not an exact number of milliseconds.- Parameters:
condition- aGIOConditionmask to wait fortimeoutUs- the maximum time (in microseconds) to wait, or -1cancellable- aGCancellable, ornull- Returns:
trueif the condition was met,falseotherwise- Throws:
GErrorException- seeGError- Since:
- 2.32
-
conditionWait
public boolean conditionWait(Set<IOCondition> condition, @Nullable Cancellable cancellable) throws GErrorException Waits forconditionto become true onsocket.When the condition is met,trueis returned.If
cancellableis cancelled before the condition is met, or if the socket has a timeout set and it is reached before the condition is met, thenfalseis returned anderror,if non-null, is set to the appropriate value (IOErrorEnum.CANCELLEDorIOErrorEnum.TIMED_OUT).See also g_socket_condition_timed_wait().
- Parameters:
condition- aGIOConditionmask to wait forcancellable- aGCancellable, ornull- Returns:
trueif the condition was met,falseotherwise- Throws:
GErrorException- seeGError- Since:
- 2.22
-
conditionWait
public boolean conditionWait(IOCondition condition, @Nullable Cancellable cancellable) throws GErrorException Waits forconditionto become true onsocket.When the condition is met,trueis returned.If
cancellableis cancelled before the condition is met, or if the socket has a timeout set and it is reached before the condition is met, thenfalseis returned anderror,if non-null, is set to the appropriate value (IOErrorEnum.CANCELLEDorIOErrorEnum.TIMED_OUT).See also g_socket_condition_timed_wait().
- Parameters:
condition- aGIOConditionmask to wait forcancellable- aGCancellable, ornull- Returns:
trueif the condition was met,falseotherwise- Throws:
GErrorException- seeGError- Since:
- 2.22
-
connect
public boolean connect(SocketAddress address, @Nullable Cancellable cancellable) throws GErrorException Connect the socket to the specified remote address.For connection oriented socket this generally means we attempt to make a connection to the
address.For a connection-less socket it sets the default address for g_socket_send() and discards all incoming datagrams from other sources.Generally connection oriented sockets can only connect once, but connection-less sockets can connect multiple times to change the default address.
If the connect call needs to do network I/O it will block, unless non-blocking I/O is enabled. Then
IOErrorEnum.PENDINGis returned and the user can be notified of the connection finishing by waiting for the G_IO_OUT condition. The result of the connection must then be checked with g_socket_check_connect_result().- Parameters:
address- aGSocketAddressspecifying the remote address.cancellable- aGCancellableornull- Returns:
trueif connected,falseon error.- Throws:
GErrorException- seeGError- Since:
- 2.22
-
connectionFactoryCreateConnection
Creates aGSocketConnectionsubclass of the right type forsocket.- Returns:
- a
GSocketConnection - Since:
- 2.22
-
createSource
Creates aGSourcethat can be attached to aGMainContextto monitor for the availability of the specifiedconditionon the socket. TheGSourcekeeps a reference to thesocket.The callback on the source is of the
GSocketSourceFunctype.It is meaningless to specify
IOCondition.ERRorIOCondition.HUPincondition;these conditions will always be reported output if they are true.cancellableif notnullcan be used to cancel the source, which will cause the source to trigger, reporting the current condition (which is likely 0 unless cancellation happened at the same time as a condition change). You can check for this in the callback using g_cancellable_is_cancelled().If this Socket has a timeout set, and it is reached before
conditionoccurs, the source will then trigger anyway, reportingIOCondition.INorIOCondition.OUTdepending oncondition.However, this Socket will have been marked as having had a timeout, and so the nextGSocketI/O method you call will then fail with aIOErrorEnum.TIMED_OUT.- Specified by:
createSourcein interfaceDatagramBased- Parameters:
condition- aGIOConditionmask to monitorcancellable- aGCancellableornull- Returns:
- a newly allocated
GSource, free with g_source_unref(). - Since:
- 2.22
-
createSource
Creates aGSourcethat can be attached to aGMainContextto monitor for the availability of the specifiedconditionon the socket. TheGSourcekeeps a reference to thesocket.The callback on the source is of the
GSocketSourceFunctype.It is meaningless to specify
IOCondition.ERRorIOCondition.HUPincondition;these conditions will always be reported output if they are true.cancellableif notnullcan be used to cancel the source, which will cause the source to trigger, reporting the current condition (which is likely 0 unless cancellation happened at the same time as a condition change). You can check for this in the callback using g_cancellable_is_cancelled().If this Socket has a timeout set, and it is reached before
conditionoccurs, the source will then trigger anyway, reportingIOCondition.INorIOCondition.OUTdepending oncondition.However, this Socket will have been marked as having had a timeout, and so the nextGSocketI/O method you call will then fail with aIOErrorEnum.TIMED_OUT.- Specified by:
createSourcein interfaceDatagramBased- Parameters:
condition- aGIOConditionmask to monitorcancellable- aGCancellableornull- Returns:
- a newly allocated
GSource, free with g_source_unref(). - Since:
- 2.22
-
getAvailableBytes
public long getAvailableBytes()Get the amount of data pending in the OS input buffer, without blocking.If this Socket is a UDP or SCTP socket, this will return the size of just the next packet, even if additional packets are buffered after that one.
Note that on Windows, this function is rather inefficient in the UDP case, and so if you know any plausible upper bound on the size of the incoming packet, it is better to just do a g_socket_receive() with a buffer of that size, rather than calling g_socket_get_available_bytes() first and then doing a receive of exactly the right size.
- Returns:
- the number of bytes that can be read from the socket without blocking or truncating, or -1 on error.
- Since:
- 2.32
-
getBlocking
public boolean getBlocking()Gets the blocking mode of the socket. For details on blocking I/O, see g_socket_set_blocking().- Returns:
trueif blocking I/O is used,falseotherwise.- Since:
- 2.22
-
getBroadcast
public boolean getBroadcast()Gets the broadcast setting onsocket;iftrue, it is possible to send packets to broadcast addresses.- Returns:
- the broadcast setting on this Socket
- Since:
- 2.32
-
getCredentials
Returns the credentials of the foreign process connected to this socket, if any (e.g. it is only supported forSocketFamily.UNIXsockets).If this operation isn't supported on the OS, the method fails with the
IOErrorEnum.NOT_SUPPORTEDerror. On Linux this is implemented by reading theSO_PEERCREDoption on the underlying socket.This method can be expected to be available on the following platforms:
- Linux since GLib 2.26
- OpenBSD since GLib 2.30
- Solaris, Illumos and OpenSolaris since GLib 2.40
- NetBSD since GLib 2.42
- macOS, tvOS, iOS since GLib 2.66
Other ways to obtain credentials from a foreign peer includes the
GUnixCredentialsMessagetype and g_unix_connection_send_credentials() / g_unix_connection_receive_credentials() functions.- Returns:
nulliferroris set, otherwise aGCredentialsobject that must be freed with g_object_unref().- Throws:
GErrorException- seeGError- Since:
- 2.26
-
getFamily
Gets the socket family of the socket.- Returns:
- a
GSocketFamily - Since:
- 2.22
-
getFd
public int getFd()Returns the underlying OS socket object. On unix this is a socket file descriptor, and on Windows this is a Winsock2 SOCKET handle. This may be useful for doing platform specific or otherwise unusual operations on the socket.- Returns:
- the file descriptor of the socket.
- Since:
- 2.22
-
getKeepalive
public boolean getKeepalive()Gets the keepalive mode of the socket. For details on this, see g_socket_set_keepalive().- Returns:
trueif keepalive is active,falseotherwise.- Since:
- 2.22
-
getListenBacklog
public int getListenBacklog()Gets the listen backlog setting of the socket. For details on this, see g_socket_set_listen_backlog().- Returns:
- the maximum number of pending connections.
- Since:
- 2.22
-
getLocalAddress
Try to get the local address of a bound socket. This is only useful if the socket has been bound to a local address, either explicitly or implicitly when connecting.- Returns:
- a
GSocketAddressornullon error. Free the returned object with g_object_unref(). - Throws:
GErrorException- seeGError- Since:
- 2.22
-
getMulticastLoopback
public boolean getMulticastLoopback()Gets the multicast loopback setting onsocket;iftrue(the default), outgoing multicast packets will be looped back to multicast listeners on the same host.- Returns:
- the multicast loopback setting on this Socket
- Since:
- 2.32
-
getMulticastTtl
public int getMulticastTtl()Gets the multicast time-to-live setting onsocket;see g_socket_set_multicast_ttl() for more details.- Returns:
- the multicast time-to-live setting on this Socket
- Since:
- 2.32
-
getOption
Gets the value of an integer-valued option onsocket,as with getsockopt(). (If you need to fetch a non-integer-valued option, you will need to call getsockopt() directly.)The
<gio/gnetworking.h>header pulls in system headers that will define most of the standard/portable socket options. For unusual socket protocols or platform-dependent options, you may need to include additional headers.Note that even for socket options that are a single byte in size,
valueis still a pointer to agintvariable, not aguchar; g_socket_get_option() will handle the conversion internally.- Parameters:
level- the "API level" of the option (eg,SOL_SOCKET)optname- the "name" of the option (eg,SO_BROADCAST)value- return location for the option value- Returns:
- success or failure. On failure,
errorwill be set, and the system error value (errnoor WSAGetLastError()) will still be set to the result of the getsockopt() call. - Throws:
GErrorException- seeGError- Since:
- 2.36
-
getProtocol
Gets the socket protocol id the socket was created with. In case the protocol is unknown, -1 is returned.- Returns:
- a protocol id, or -1 if unknown
- Since:
- 2.22
-
getRemoteAddress
Try to get the remote address of a connected socket. This is only useful for connection oriented sockets that have been connected.- Returns:
- a
GSocketAddressornullon error. Free the returned object with g_object_unref(). - Throws:
GErrorException- seeGError- Since:
- 2.22
-
getSocketType
Gets the socket type of the socket.- Returns:
- a
GSocketType - Since:
- 2.22
-
getTimeout
public int getTimeout()Gets the timeout setting of the socket. For details on this, see g_socket_set_timeout().- Returns:
- the timeout in seconds
- Since:
- 2.26
-
getTtl
public int getTtl()Gets the unicast time-to-live setting onsocket;see g_socket_set_ttl() for more details.- Returns:
- the time-to-live setting on this Socket
- Since:
- 2.32
-
isClosed
public boolean isClosed()Checks whether a socket is closed.- Returns:
trueif socket is closed,falseotherwise- Since:
- 2.22
-
isConnected
public boolean isConnected()Check whether the socket is connected. This is only useful for connection-oriented sockets.If using g_socket_shutdown(), this function will return
trueuntil the socket has been shut down for reading and writing. If you do a non-blocking connect, this function will not returntrueuntil after you call g_socket_check_connect_result().- Returns:
trueif socket is connected,falseotherwise.- Since:
- 2.22
-
joinMulticastGroup
public boolean joinMulticastGroup(InetAddress group, boolean sourceSpecific, @Nullable String iface) throws GErrorException Registers this Socket to receive multicast messages sent togroup.this Socket must be aSocketType.DATAGRAMsocket, and must have been bound to an appropriate interface and port with g_socket_bind().If
ifaceisnull, the system will automatically pick an interface to bind to based ongroup.If
sourceSpecificistrue, source-specific multicast as defined in RFC 4604 is used. Note that on older platforms this may fail with aIOErrorEnum.NOT_SUPPORTEDerror.To bind to a given source-specific multicast address, use g_socket_join_multicast_group_ssm() instead.
- Parameters:
group- aGInetAddressspecifying the group address to join.sourceSpecific-trueif source-specific multicast should be usediface- Name of the interface to use, ornull- Returns:
trueon success,falseon error.- Throws:
GErrorException- seeGError- Since:
- 2.32
-
joinMulticastGroupSsm
public boolean joinMulticastGroupSsm(InetAddress group, @Nullable InetAddress sourceSpecific, @Nullable String iface) throws GErrorException Registers this Socket to receive multicast messages sent togroup.this Socket must be aSocketType.DATAGRAMsocket, and must have been bound to an appropriate interface and port with g_socket_bind().If
ifaceisnull, the system will automatically pick an interface to bind to based ongroup.If
sourceSpecificis notnull, use source-specific multicast as defined in RFC 4604. Note that on older platforms this may fail with aIOErrorEnum.NOT_SUPPORTEDerror.Note that this function can be called multiple times for the same
groupwith differentsourceSpecificin order to receive multicast packets from more than one source.- Parameters:
group- aGInetAddressspecifying the group address to join.sourceSpecific- aGInetAddressspecifying the source-specific multicast address ornullto ignore.iface- Name of the interface to use, ornull- Returns:
trueon success,falseon error.- Throws:
GErrorException- seeGError- Since:
- 2.56
-
leaveMulticastGroup
public boolean leaveMulticastGroup(InetAddress group, boolean sourceSpecific, @Nullable String iface) throws GErrorException Removes this Socket from the multicast group defined bygroup,iface,andsourceSpecific(which must all have the same values they had when you joined the group).this Socket remains bound to its address and port, and can still receive unicast messages after calling this.
To unbind to a given source-specific multicast address, use g_socket_leave_multicast_group_ssm() instead.
- Parameters:
group- aGInetAddressspecifying the group address to leave.sourceSpecific-trueif source-specific multicast was usediface- Interface used- Returns:
trueon success,falseon error.- Throws:
GErrorException- seeGError- Since:
- 2.32
-
leaveMulticastGroupSsm
public boolean leaveMulticastGroupSsm(InetAddress group, @Nullable InetAddress sourceSpecific, @Nullable String iface) throws GErrorException Removes this Socket from the multicast group defined bygroup,iface,andsourceSpecific(which must all have the same values they had when you joined the group).this Socket remains bound to its address and port, and can still receive unicast messages after calling this.
- Parameters:
group- aGInetAddressspecifying the group address to leave.sourceSpecific- aGInetAddressspecifying the source-specific multicast address ornullto ignore.iface- Name of the interface to use, ornull- Returns:
trueon success,falseon error.- Throws:
GErrorException- seeGError- Since:
- 2.56
-
listen
Marks the socket as a server socket, i.e. a socket that is used to accept incoming requests using g_socket_accept().Before calling this the socket must be bound to a local address using g_socket_bind().
To set the maximum amount of outstanding clients, use g_socket_set_listen_backlog().
- Returns:
trueon success,falseon error.- Throws:
GErrorException- seeGError- Since:
- 2.22
-
receive
public long receive(@Nullable Out<byte[]> buffer, @Nullable Cancellable cancellable) throws GErrorException Receive data (up tosizebytes) from a socket. This is mainly used by connection-oriented sockets; it is identical to g_socket_receive_from() withaddressset tonull.For
SocketType.DATAGRAMandSocketType.SEQPACKETsockets, g_socket_receive() will always read either 0 or 1 complete messages from the socket. If the received message is too large to fit inbuffer,then the data beyondsizebytes will be discarded, without any explicit indication that this has occurred.For
SocketType.STREAMsockets, g_socket_receive() can return any number of bytes, up tosize.If more thansizebytes have been received, the additional data will be returned in future calls to g_socket_receive().If the socket is in blocking mode the call will block until there is some data to receive, the connection is closed, or there is an error. If there is no data available and the socket is in non-blocking mode, a
IOErrorEnum.WOULD_BLOCKerror will be returned. To be notified when data is available, wait for theIOCondition.INcondition.On error -1 is returned and
erroris set accordingly.- Parameters:
buffer- a buffer to read data into (which should be at leastsizebytes long).cancellable- aGCancellableornull- Returns:
- Number of bytes read, or 0 if the connection was closed by the peer, or -1 on error
- Throws:
GErrorException- seeGError- Since:
- 2.22
-
receiveBytes
public byte[] receiveBytes(long size, long timeoutUs, @Nullable Cancellable cancellable) throws GErrorException Receives data (up tosizebytes) from a socket.This function is a variant of
receive(org.javagi.base.Out<byte[]>, org.gnome.gio.Cancellable)which returns aGLib.Bytesrather than a plain buffer.Pass
-1totimeoutUsto block indefinitely until data is received (or the connection is closed, or there is an error). Pass0to use the default timeout fromGio.Socket:timeout, or pass a positive number to wait for that many microseconds for data before returningG_IO_ERROR_TIMED_OUT.- Parameters:
size- the number of bytes you want to read from the sockettimeoutUs- the timeout to wait for, in microseconds, or-1to block indefinitelycancellable- aGCancellable, orNULL- Returns:
- a bytes buffer containing the
received bytes, or
NULLon error - Throws:
GErrorException- seeGError- Since:
- 2.80
-
receiveBytesFrom
public byte[] receiveBytesFrom(@Nullable Out<SocketAddress> address, long size, long timeoutUs, @Nullable Cancellable cancellable) throws GErrorException Receive data (up tosizebytes) from a socket.This function is a variant of
receiveFrom(org.javagi.base.Out<org.gnome.gio.SocketAddress>, org.javagi.base.Out<byte[]>, org.gnome.gio.Cancellable)which returns aGLib.Bytesrather than a plain buffer.If
addressis non-nullthenaddresswill be set equal to the source address of the received packet.The
addressis owned by the caller.Pass
-1totimeoutUsto block indefinitely until data is received (or the connection is closed, or there is an error). Pass0to use the default timeout fromGio.Socket:timeout, or pass a positive number to wait for that many microseconds for data before returningG_IO_ERROR_TIMED_OUT.- Parameters:
address- return location for aGSocketAddresssize- the number of bytes you want to read from the sockettimeoutUs- the timeout to wait for, in microseconds, or-1to block indefinitelycancellable- aGCancellable, orNULL- Returns:
- a bytes buffer containing the
received bytes, or
NULLon error - Throws:
GErrorException- seeGError- Since:
- 2.80
-
receiveFrom
public long receiveFrom(@Nullable Out<SocketAddress> address, @Nullable Out<byte[]> buffer, @Nullable Cancellable cancellable) throws GErrorException Receive data (up tosizebytes) from a socket.If
addressis non-nullthenaddresswill be set equal to the source address of the received packet.addressis owned by the caller.See g_socket_receive() for additional information.
- Parameters:
address- a pointer to aGSocketAddresspointer, ornullbuffer- a buffer to read data into (which should be at leastsizebytes long).cancellable- aGCancellableornull- Returns:
- Number of bytes read, or 0 if the connection was closed by the peer, or -1 on error
- Throws:
GErrorException- seeGError- Since:
- 2.22
-
receiveMessage
public long receiveMessage(@Nullable Out<SocketAddress> address, @Nullable InputVector @Nullable [] vectors, @Nullable Out<SocketControlMessage[]> messages, Out<Integer> flags, @Nullable Cancellable cancellable) throws GErrorException Receive data from a socket. For receiving multiple messages, see g_socket_receive_messages(); for easier use, see g_socket_receive() and g_socket_receive_from().If
addressis non-nullthenaddresswill be set equal to the source address of the received packet.addressis owned by the caller.vectormust point to an array ofGInputVectorstructs andnumVectorsmust be the length of this array. These structs describe the buffers that received data will be scattered into. IfnumVectorsis -1, thenvectorsis assumed to be terminated by aGInputVectorwith anullbuffer pointer.As a special case, if
numVectorsis 0 (in which case,vectorsmay of course benull), then a single byte is received and discarded. This is to facilitate the common practice of sending a single '\\0' byte for the purposes of transferring ancillary data.messages,if non-null, will be set to point to a newly-allocated array ofGSocketControlMessageinstances ornullif no such messages was received. These correspond to the control messages received from the kernel, oneGSocketControlMessageper message from the kernel. This array isnull-terminated and must be freed by the caller using g_free() after calling g_object_unref() on each element. Ifmessagesisnull, any control messages received will be discarded.numMessages,if non-null, will be set to the number of control messages received.If both
messagesandnumMessagesare non-null, thennumMessagesgives the number ofGSocketControlMessageinstances inmessages(ie: not including thenullterminator).flagsis an in/out parameter. The commonly available arguments for this are available in theGSocketMsgFlagsenum, but the values there are the same as the system values, and the flags are passed in as-is, so you can pass in system-specific flags too (and g_socket_receive_message() may pass system-specific flags out). Flags passed in to the parameter affect the receive operation; flags returned out of it are relevant to the specific returned message.As with g_socket_receive(), data may be discarded if this Socket is
SocketType.DATAGRAMorSocketType.SEQPACKETand you do not provide enough buffer space to read a complete message. You can passSocketMsgFlags.PEEKinflagsto peek at the current message without removing it from the receive queue, but there is no portable way to find out the length of the message other than by reading it into a sufficiently-large buffer.If the socket is in blocking mode the call will block until there is some data to receive, the connection is closed, or there is an error. If there is no data available and the socket is in non-blocking mode, a
IOErrorEnum.WOULD_BLOCKerror will be returned. To be notified when data is available, wait for theIOCondition.INcondition.On error -1 is returned and
erroris set accordingly.- Parameters:
address- a pointer to aGSocketAddresspointer, ornullvectors- an array ofGInputVectorstructsmessages- a pointer which may be filled with an array ofGSocketControlMessages, ornullflags- a pointer to an int containingGSocketMsgFlagsflags, which may additionally contain other platform specific flagscancellable- aGCancellableornull- Returns:
- Number of bytes read, or 0 if the connection was closed by the peer, or -1 on error
- Throws:
GErrorException- seeGError- Since:
- 2.22
-
receiveMessages
public int receiveMessages(@Nullable InputMessage @Nullable [] messages, int flags, @Nullable Cancellable cancellable) throws GErrorException Receive multiple data messages from this Socket in one go. This is the most complicated and fully-featured version of this call. For easier use, see g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().messagesmust point to an array ofGInputMessagestructs andnumMessagesmust be the length of this array. EachGInputMessagecontains a pointer to an array ofGInputVectorstructs describing the buffers that the data received in each message will be written to. Using multipleGInputVectorsis more memory-efficient than manually copying data out of a single buffer to multiple sources, and more system-call-efficient than making multiple calls to g_socket_receive(), such as in scenarios where a lot of data packets need to be received (e.g. high-bandwidth video streaming over RTP/UDP).flagsmodify how all messages are received. The commonly available arguments for this are available in theGSocketMsgFlagsenum, but the values there are the same as the system values, and the flags are passed in as-is, so you can pass in system-specific flags too. These flags affect the overall receive operation. Flags affecting individual messages are returned inGInputMessage.flags.The other members of
GInputMessageare treated as described in its documentation.If
GSocket:blocking istruethe call will block untilnumMessageshave been received, or the end of the stream is reached.If
GSocket:blocking isfalsethe call will return up tonumMessageswithout blocking, orIOErrorEnum.WOULD_BLOCKif no messages are queued in the operating system to be received.In blocking mode, if
GSocket:timeout is positive and is reached before any messages are received,IOErrorEnum.TIMED_OUTis returned, otherwise up tonumMessagesare returned. (Note: This is effectively the behaviour ofMSG_WAITFORONEwith recvmmsg().)To be notified when messages are available, wait for the
IOCondition.INcondition. Note though that you may still receiveIOErrorEnum.WOULD_BLOCKfrom g_socket_receive_messages() even if you were previously notified of aIOCondition.INcondition.If the remote peer closes the connection, any messages queued in the operating system will be returned, and subsequent calls to g_socket_receive_messages() will return 0 (with no error set).
On error -1 is returned and
erroris set accordingly. An error will only be returned if zero messages could be received; otherwise the number of messages successfully received before the error will be returned.- Parameters:
messages- an array ofGInputMessagestructsflags- an int containingGSocketMsgFlagsflags for the overall operation, which may additionally contain other platform specific flagscancellable- aGCancellableornull- Returns:
- number of messages received, or -1 on error. Note that the number
of messages received may be smaller than
numMessagesif in non-blocking mode, if the peer closed the connection, or ifnumMessageswas larger thanUIO_MAXIOV(1024), in which case the caller may re-try to receive the remaining messages. - Throws:
GErrorException- seeGError- Since:
- 2.48
-
receiveWithBlocking
public long receiveWithBlocking(@Nullable Out<byte[]> buffer, boolean blocking, @Nullable Cancellable cancellable) throws GErrorException This behaves exactly the same as g_socket_receive(), except that the choice of blocking or non-blocking behavior is determined by theblockingargument rather than bysocket'sproperties.- Parameters:
buffer- a buffer to read data into (which should be at leastsizebytes long).blocking- whether to do blocking or non-blocking I/Ocancellable- aGCancellableornull- Returns:
- Number of bytes read, or 0 if the connection was closed by the peer, or -1 on error
- Throws:
GErrorException- seeGError- Since:
- 2.26
-
send
public long send(@org.jspecify.annotations.Nullable byte @Nullable [] buffer, @Nullable Cancellable cancellable) throws GErrorException Tries to sendsizebytes frombufferon the socket. This is mainly used by connection-oriented sockets; it is identical to g_socket_send_to() withaddressset tonull.If the socket is in blocking mode the call will block until there is space for the data in the socket queue. If there is no space available and the socket is in non-blocking mode a
IOErrorEnum.WOULD_BLOCKerror will be returned. To be notified when space is available, wait for theIOCondition.OUTcondition. Note though that you may still receiveIOErrorEnum.WOULD_BLOCKfrom g_socket_send() even if you were previously notified of aIOCondition.OUTcondition. (On Windows in particular, this is very common due to the way the underlying APIs work.)On error -1 is returned and
erroris set accordingly.- Parameters:
buffer- the buffer containing the data to send.cancellable- aGCancellableornull- Returns:
- Number of bytes written (which may be less than
size),or -1 on error - Throws:
GErrorException- seeGError- Since:
- 2.22
-
sendMessage
public long sendMessage(@Nullable SocketAddress address, @Nullable OutputVector @Nullable [] vectors, @Nullable SocketControlMessage @Nullable [] messages, int flags, @Nullable Cancellable cancellable) throws GErrorException Send data toaddressonsocket.For sending multiple messages see g_socket_send_messages(); for easier use, see g_socket_send() and g_socket_send_to().If
addressisnullthen the message is sent to the default receiver (set by g_socket_connect()).vectorsmust point to an array ofGOutputVectorstructs andnumVectorsmust be the length of this array. (IfnumVectorsis -1, thenvectorsis assumed to be terminated by aGOutputVectorwith anullbuffer pointer.) TheGOutputVectorstructs describe the buffers that the sent data will be gathered from. Using multipleGOutputVectorsis more memory-efficient than manually copying data from multiple sources into a single buffer, and more network-efficient than making multiple calls to g_socket_send().messages,if non-null, is taken to point to an array ofnumMessagesGSocketControlMessageinstances. These correspond to the control messages to be sent on the socket. IfnumMessagesis -1 thenmessagesis treated as anull-terminated array.flagsmodify how the message is sent. The commonly available arguments for this are available in theGSocketMsgFlagsenum, but the values there are the same as the system values, and the flags are passed in as-is, so you can pass in system-specific flags too.If the socket is in blocking mode the call will block until there is space for the data in the socket queue. If there is no space available and the socket is in non-blocking mode a
IOErrorEnum.WOULD_BLOCKerror will be returned. To be notified when space is available, wait for theIOCondition.OUTcondition. Note though that you may still receiveIOErrorEnum.WOULD_BLOCKfrom g_socket_send() even if you were previously notified of aIOCondition.OUTcondition. (On Windows in particular, this is very common due to the way the underlying APIs work.)The sum of the sizes of each
GOutputVectorin vectors must not be greater thanG_MAXSSIZE. If the message can be larger than this, then it is mandatory to use the g_socket_send_message_with_timeout() function.On error -1 is returned and
erroris set accordingly.- Parameters:
address- aGSocketAddress, ornullvectors- an array ofGOutputVectorstructsmessages- a pointer to an array ofGSocketControlMessages, ornull.flags- an int containingGSocketMsgFlagsflags, which may additionally contain other platform specific flagscancellable- aGCancellableornull- Returns:
- Number of bytes written (which may be less than
size),or -1 on error - Throws:
GErrorException- seeGError- Since:
- 2.22
-
sendMessageWithTimeout
public PollableReturn sendMessageWithTimeout(@Nullable SocketAddress address, @Nullable OutputVector @Nullable [] vectors, @Nullable SocketControlMessage @Nullable [] messages, int flags, long timeoutUs, @Nullable Out<Long> bytesWritten, @Nullable Cancellable cancellable) throws GErrorException This behaves exactly the same as g_socket_send_message(), except that the choice of timeout behavior is determined by thetimeoutUsargument rather than bysocket'sproperties.On error
PollableReturn.FAILEDis returned anderroris set accordingly, or if the socket is currently not writablePollableReturn.WOULD_BLOCKis returned.bytesWrittenwill contain 0 in both cases.- Parameters:
address- aGSocketAddress, ornullvectors- an array ofGOutputVectorstructsmessages- a pointer to an array ofGSocketControlMessages, ornull.flags- an int containingGSocketMsgFlagsflags, which may additionally contain other platform specific flagstimeoutUs- the maximum time (in microseconds) to wait, or -1bytesWritten- location to store the number of bytes that were written to the socketcancellable- aGCancellableornull- Returns:
PollableReturn.OKif all data was successfully written,PollableReturn.WOULD_BLOCKif the socket is currently not writable, orPollableReturn.FAILEDif an error happened anderroris set.- Throws:
GErrorException- seeGError- Since:
- 2.60
-
sendMessages
public int sendMessages(@Nullable OutputMessage @Nullable [] messages, int flags, @Nullable Cancellable cancellable) throws GErrorException Send multiple data messages from this Socket in one go. This is the most complicated and fully-featured version of this call. For easier use, see g_socket_send(), g_socket_send_to(), and g_socket_send_message().messagesmust point to an array ofGOutputMessagestructs andnumMessagesmust be the length of this array. EachGOutputMessagecontains an address to send the data to, and a pointer to an array ofGOutputVectorstructs to describe the buffers that the data to be sent for each message will be gathered from. Using multipleGOutputVectorsis more memory-efficient than manually copying data from multiple sources into a single buffer, and more network-efficient than making multiple calls to g_socket_send(). Sending multiple messages in one go avoids the overhead of making a lot of syscalls in scenarios where a lot of data packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP), or where the same data needs to be sent to multiple recipients.flagsmodify how the message is sent. The commonly available arguments for this are available in theGSocketMsgFlagsenum, but the values there are the same as the system values, and the flags are passed in as-is, so you can pass in system-specific flags too.If the socket is in blocking mode the call will block until there is space for all the data in the socket queue. If there is no space available and the socket is in non-blocking mode a
IOErrorEnum.WOULD_BLOCKerror will be returned if no data was written at all, otherwise the number of messages sent will be returned. To be notified when space is available, wait for theIOCondition.OUTcondition. Note though that you may still receiveIOErrorEnum.WOULD_BLOCKfrom g_socket_send() even if you were previously notified of aIOCondition.OUTcondition. (On Windows in particular, this is very common due to the way the underlying APIs work.)On error -1 is returned and
erroris set accordingly. An error will only be returned if zero messages could be sent; otherwise the number of messages successfully sent before the error will be returned.- Parameters:
messages- an array ofGOutputMessagestructsflags- an int containingGSocketMsgFlagsflags, which may additionally contain other platform specific flagscancellable- aGCancellableornull- Returns:
- number of messages sent, or -1 on error. Note that the number of
messages sent may be smaller than
numMessagesif the socket is non-blocking or ifnumMessageswas larger than UIO_MAXIOV (1024), in which case the caller may re-try to send the remaining messages. - Throws:
GErrorException- seeGError- Since:
- 2.44
-
sendTo
public long sendTo(@Nullable SocketAddress address, @org.jspecify.annotations.Nullable byte @Nullable [] buffer, @Nullable Cancellable cancellable) throws GErrorException Tries to sendsizebytes frombuffertoaddress.Ifaddressisnullthen the message is sent to the default receiver (set by g_socket_connect()).See g_socket_send() for additional information.
- Parameters:
address- aGSocketAddress, ornullbuffer- the buffer containing the data to send.cancellable- aGCancellableornull- Returns:
- Number of bytes written (which may be less than
size),or -1 on error - Throws:
GErrorException- seeGError- Since:
- 2.22
-
sendWithBlocking
public long sendWithBlocking(@org.jspecify.annotations.Nullable byte @Nullable [] buffer, boolean blocking, @Nullable Cancellable cancellable) throws GErrorException This behaves exactly the same as g_socket_send(), except that the choice of blocking or non-blocking behavior is determined by theblockingargument rather than bysocket'sproperties.- Parameters:
buffer- the buffer containing the data to send.blocking- whether to do blocking or non-blocking I/Ocancellable- aGCancellableornull- Returns:
- Number of bytes written (which may be less than
size),or -1 on error - Throws:
GErrorException- seeGError- Since:
- 2.26
-
setBlocking
public void setBlocking(boolean blocking) Sets the blocking mode of the socket. In blocking mode all operations (which don’t take an explicit blocking parameter) block until they succeed or there is an error. In non-blocking mode all functions return results immediately or with aIOErrorEnum.WOULD_BLOCKerror.All sockets are created in blocking mode. However, note that the platform level socket is always non-blocking, and blocking mode is a GSocket level feature.
- Parameters:
blocking- Whether to use blocking I/O or not.- Since:
- 2.22
-
setBroadcast
public void setBroadcast(boolean broadcast) Sets whether this Socket should allow sending to broadcast addresses. This isfalseby default.- Parameters:
broadcast- whether this Socket should allow sending to broadcast addresses- Since:
- 2.32
-
setKeepalive
public void setKeepalive(boolean keepalive) Sets or unsets theSO_KEEPALIVEflag on the underlying socket. When this flag is set on a socket, the system will attempt to verify that the remote socket endpoint is still present if a sufficiently long period of time passes with no data being exchanged. If the system is unable to verify the presence of the remote endpoint, it will automatically close the connection.This option is only functional on certain kinds of sockets. (Notably,
SocketProtocol.TCPsockets.)The exact time between pings is system- and protocol-dependent, but will normally be at least two hours. Most commonly, you would set this flag on a server socket if you want to allow clients to remain idle for long periods of time, but also want to ensure that connections are eventually garbage-collected if clients crash or become unreachable.
- Parameters:
keepalive- Value for the keepalive flag- Since:
- 2.22
-
setListenBacklog
public void setListenBacklog(int backlog) Sets the maximum number of outstanding connections allowed when listening on this socket. If more clients than this are connecting to the socket and the application is not handling them on time then the new connections will be refused.Note that this must be called before g_socket_listen() and has no effect if called after that.
- Parameters:
backlog- the maximum number of pending connections.- Since:
- 2.22
-
setMulticastLoopback
public void setMulticastLoopback(boolean loopback) Sets whether outgoing multicast packets will be received by sockets listening on that multicast address on the same host. This istrueby default.- Parameters:
loopback- whether this Socket should receive messages sent to its multicast groups from the local host- Since:
- 2.32
-
setMulticastTtl
public void setMulticastTtl(int ttl) Sets the time-to-live for outgoing multicast datagrams onsocket.By default, this is 1, meaning that multicast packets will not leave the local network.- Parameters:
ttl- the time-to-live value for all multicast datagrams on this Socket- Since:
- 2.32
-
setOption
Sets the value of an integer-valued option onsocket,as with setsockopt(). (If you need to set a non-integer-valued option, you will need to call setsockopt() directly.)The
<gio/gnetworking.h>header pulls in system headers that will define most of the standard/portable socket options. For unusual socket protocols or platform-dependent options, you may need to include additional headers.- Parameters:
level- the "API level" of the option (eg,SOL_SOCKET)optname- the "name" of the option (eg,SO_BROADCAST)value- the value to set the option to- Returns:
- success or failure. On failure,
errorwill be set, and the system error value (errnoor WSAGetLastError()) will still be set to the result of the setsockopt() call. - Throws:
GErrorException- seeGError- Since:
- 2.36
-
setTimeout
public void setTimeout(int timeout) Sets the time in seconds after which I/O operations on this Socket will time out if they have not yet completed.On a blocking socket, this means that any blocking
GSocketoperation will time out aftertimeoutseconds of inactivity, returningIOErrorEnum.TIMED_OUT.On a non-blocking socket, calls to g_socket_condition_wait() will also fail with
IOErrorEnum.TIMED_OUTafter the given time. Sources created with g_socket_create_source() will trigger aftertimeoutseconds of inactivity, with the requested condition set, at which point calling g_socket_receive(), g_socket_send(), g_socket_check_connect_result(), etc, will fail withIOErrorEnum.TIMED_OUT.If
timeoutis 0 (the default), operations will never time out on their own.Note that if an I/O operation is interrupted by a signal, this may cause the timeout to be reset.
- Parameters:
timeout- the timeout forsocket,in seconds, or 0 for none- Since:
- 2.26
-
setTtl
public void setTtl(int ttl) Sets the time-to-live for outgoing unicast packets onsocket.By default the platform-specific default value is used.- Parameters:
ttl- the time-to-live value for all unicast packets on this Socket- Since:
- 2.32
-
shutdown
Shut down part or all of a full-duplex connection.If
shutdownReadistruethen the receiving side of the connection is shut down, and further reading is disallowed.If
shutdownWriteistruethen the sending side of the connection is shut down, and further writing is disallowed.It is allowed for both
shutdownReadandshutdownWriteto betrue.One example where it is useful to shut down only one side of a connection is graceful disconnect for TCP connections where you close the sending side, then wait for the other side to close the connection, thus ensuring that the other side saw all sent data.
- Parameters:
shutdownRead- whether to shut down the read sideshutdownWrite- whether to shut down the write side- Returns:
trueon success,falseon error- Throws:
GErrorException- seeGError- Since:
- 2.22
-
speaksIpv4
public boolean speaksIpv4()Checks if a socket is capable of speaking IPv4.IPv4 sockets are capable of speaking IPv4. On some operating systems and under some combinations of circumstances IPv6 sockets are also capable of speaking IPv4. See RFC 3493 section 3.7 for more information.
No other types of sockets are currently considered as being capable of speaking IPv4.
- Returns:
trueif this socket can be used with IPv4.- Since:
- 2.22
-
builder
ASocket.Builderobject constructs aSocketwith the specified properties. Use the variousset...()methods to set properties, and finish construction withSocket.Builder.build().- Returns:
- the builder object
-