Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/net/ServerSocket.java
38829 views
1
/*
2
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation. Oracle designates this
8
* particular file as subject to the "Classpath" exception as provided
9
* by Oracle in the LICENSE file that accompanied this code.
10
*
11
* This code is distributed in the hope that it will be useful, but WITHOUT
12
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14
* version 2 for more details (a copy is included in the LICENSE file that
15
* accompanied this code).
16
*
17
* You should have received a copy of the GNU General Public License version
18
* 2 along with this work; if not, write to the Free Software Foundation,
19
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
*
21
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22
* or visit www.oracle.com if you need additional information or have any
23
* questions.
24
*/
25
26
package java.net;
27
28
import java.io.FileDescriptor;
29
import java.io.IOException;
30
import java.nio.channels.ServerSocketChannel;
31
import java.security.AccessController;
32
import java.security.PrivilegedExceptionAction;
33
34
import sun.security.util.SecurityConstants;
35
36
/**
37
* This class implements server sockets. A server socket waits for
38
* requests to come in over the network. It performs some operation
39
* based on that request, and then possibly returns a result to the requester.
40
* <p>
41
* The actual work of the server socket is performed by an instance
42
* of the {@code SocketImpl} class. An application can
43
* change the socket factory that creates the socket
44
* implementation to configure itself to create sockets
45
* appropriate to the local firewall.
46
*
47
* @author unascribed
48
* @see java.net.SocketImpl
49
* @see java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
50
* @see java.nio.channels.ServerSocketChannel
51
* @since JDK1.0
52
*/
53
public
54
class ServerSocket implements java.io.Closeable {
55
/**
56
* Various states of this socket.
57
*/
58
private boolean created = false;
59
private boolean bound = false;
60
private boolean closed = false;
61
private Object closeLock = new Object();
62
63
/**
64
* The implementation of this Socket.
65
*/
66
private SocketImpl impl;
67
68
/**
69
* Are we using an older SocketImpl?
70
*/
71
private boolean oldImpl = false;
72
73
/**
74
* Package-private constructor to create a ServerSocket associated with
75
* the given SocketImpl.
76
*
77
* @throws SecurityException if a security manager is set and
78
* its {@code checkPermission} method doesn't allow
79
* {@code NetPermission("setSocketImpl")}.
80
*/
81
ServerSocket(SocketImpl impl) {
82
checkPermission();
83
this.impl = impl;
84
impl.setServerSocket(this);
85
}
86
87
private static Void checkPermission() {
88
SecurityManager sm = System.getSecurityManager();
89
if (sm != null) {
90
sm.checkPermission(SecurityConstants.SET_SOCKETIMPL_PERMISSION);
91
}
92
return null;
93
}
94
95
/**
96
* Creates an unbound server socket.
97
*
98
* @exception IOException IO error when opening the socket.
99
* @revised 1.4
100
*/
101
public ServerSocket() throws IOException {
102
setImpl();
103
}
104
105
/**
106
* Creates a server socket, bound to the specified port. A port number
107
* of {@code 0} means that the port number is automatically
108
* allocated, typically from an ephemeral port range. This port
109
* number can then be retrieved by calling {@link #getLocalPort getLocalPort}.
110
* <p>
111
* The maximum queue length for incoming connection indications (a
112
* request to connect) is set to {@code 50}. If a connection
113
* indication arrives when the queue is full, the connection is refused.
114
* <p>
115
* If the application has specified a server socket factory, that
116
* factory's {@code createSocketImpl} method is called to create
117
* the actual socket implementation. Otherwise a "plain" socket is created.
118
* <p>
119
* If there is a security manager,
120
* its {@code checkListen} method is called
121
* with the {@code port} argument
122
* as its argument to ensure the operation is allowed.
123
* This could result in a SecurityException.
124
*
125
*
126
* @param port the port number, or {@code 0} to use a port
127
* number that is automatically allocated.
128
*
129
* @exception IOException if an I/O error occurs when opening the socket.
130
* @exception SecurityException
131
* if a security manager exists and its {@code checkListen}
132
* method doesn't allow the operation.
133
* @exception IllegalArgumentException if the port parameter is outside
134
* the specified range of valid port values, which is between
135
* 0 and 65535, inclusive.
136
*
137
* @see java.net.SocketImpl
138
* @see java.net.SocketImplFactory#createSocketImpl()
139
* @see java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
140
* @see SecurityManager#checkListen
141
*/
142
public ServerSocket(int port) throws IOException {
143
this(port, 50, null);
144
}
145
146
/**
147
* Creates a server socket and binds it to the specified local port
148
* number, with the specified backlog.
149
* A port number of {@code 0} means that the port number is
150
* automatically allocated, typically from an ephemeral port range.
151
* This port number can then be retrieved by calling
152
* {@link #getLocalPort getLocalPort}.
153
* <p>
154
* The maximum queue length for incoming connection indications (a
155
* request to connect) is set to the {@code backlog} parameter. If
156
* a connection indication arrives when the queue is full, the
157
* connection is refused.
158
* <p>
159
* If the application has specified a server socket factory, that
160
* factory's {@code createSocketImpl} method is called to create
161
* the actual socket implementation. Otherwise a "plain" socket is created.
162
* <p>
163
* If there is a security manager,
164
* its {@code checkListen} method is called
165
* with the {@code port} argument
166
* as its argument to ensure the operation is allowed.
167
* This could result in a SecurityException.
168
*
169
* The {@code backlog} argument is the requested maximum number of
170
* pending connections on the socket. Its exact semantics are implementation
171
* specific. In particular, an implementation may impose a maximum length
172
* or may choose to ignore the parameter altogther. The value provided
173
* should be greater than {@code 0}. If it is less than or equal to
174
* {@code 0}, then an implementation specific default will be used.
175
* <P>
176
*
177
* @param port the port number, or {@code 0} to use a port
178
* number that is automatically allocated.
179
* @param backlog requested maximum length of the queue of incoming
180
* connections.
181
*
182
* @exception IOException if an I/O error occurs when opening the socket.
183
* @exception SecurityException
184
* if a security manager exists and its {@code checkListen}
185
* method doesn't allow the operation.
186
* @exception IllegalArgumentException if the port parameter is outside
187
* the specified range of valid port values, which is between
188
* 0 and 65535, inclusive.
189
*
190
* @see java.net.SocketImpl
191
* @see java.net.SocketImplFactory#createSocketImpl()
192
* @see java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
193
* @see SecurityManager#checkListen
194
*/
195
public ServerSocket(int port, int backlog) throws IOException {
196
this(port, backlog, null);
197
}
198
199
/**
200
* Create a server with the specified port, listen backlog, and
201
* local IP address to bind to. The <i>bindAddr</i> argument
202
* can be used on a multi-homed host for a ServerSocket that
203
* will only accept connect requests to one of its addresses.
204
* If <i>bindAddr</i> is null, it will default accepting
205
* connections on any/all local addresses.
206
* The port must be between 0 and 65535, inclusive.
207
* A port number of {@code 0} means that the port number is
208
* automatically allocated, typically from an ephemeral port range.
209
* This port number can then be retrieved by calling
210
* {@link #getLocalPort getLocalPort}.
211
*
212
* <P>If there is a security manager, this method
213
* calls its {@code checkListen} method
214
* with the {@code port} argument
215
* as its argument to ensure the operation is allowed.
216
* This could result in a SecurityException.
217
*
218
* The {@code backlog} argument is the requested maximum number of
219
* pending connections on the socket. Its exact semantics are implementation
220
* specific. In particular, an implementation may impose a maximum length
221
* or may choose to ignore the parameter altogther. The value provided
222
* should be greater than {@code 0}. If it is less than or equal to
223
* {@code 0}, then an implementation specific default will be used.
224
* <P>
225
* @param port the port number, or {@code 0} to use a port
226
* number that is automatically allocated.
227
* @param backlog requested maximum length of the queue of incoming
228
* connections.
229
* @param bindAddr the local InetAddress the server will bind to
230
*
231
* @throws SecurityException if a security manager exists and
232
* its {@code checkListen} method doesn't allow the operation.
233
*
234
* @throws IOException if an I/O error occurs when opening the socket.
235
* @exception IllegalArgumentException if the port parameter is outside
236
* the specified range of valid port values, which is between
237
* 0 and 65535, inclusive.
238
*
239
* @see SocketOptions
240
* @see SocketImpl
241
* @see SecurityManager#checkListen
242
* @since JDK1.1
243
*/
244
public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException {
245
setImpl();
246
if (port < 0 || port > 0xFFFF)
247
throw new IllegalArgumentException(
248
"Port value out of range: " + port);
249
if (backlog < 1)
250
backlog = 50;
251
try {
252
bind(new InetSocketAddress(bindAddr, port), backlog);
253
} catch(SecurityException e) {
254
close();
255
throw e;
256
} catch(IOException e) {
257
close();
258
throw e;
259
}
260
}
261
262
/**
263
* Get the {@code SocketImpl} attached to this socket, creating
264
* it if necessary.
265
*
266
* @return the {@code SocketImpl} attached to that ServerSocket.
267
* @throws SocketException if creation fails.
268
* @since 1.4
269
*/
270
SocketImpl getImpl() throws SocketException {
271
if (!created)
272
createImpl();
273
return impl;
274
}
275
276
private void checkOldImpl() {
277
if (impl == null)
278
return;
279
// SocketImpl.connect() is a protected method, therefore we need to use
280
// getDeclaredMethod, therefore we need permission to access the member
281
try {
282
AccessController.doPrivileged(
283
new PrivilegedExceptionAction<Void>() {
284
public Void run() throws NoSuchMethodException {
285
impl.getClass().getDeclaredMethod("connect",
286
SocketAddress.class,
287
int.class);
288
return null;
289
}
290
});
291
} catch (java.security.PrivilegedActionException e) {
292
oldImpl = true;
293
}
294
}
295
296
private void setImpl() {
297
if (factory != null) {
298
impl = factory.createSocketImpl();
299
checkOldImpl();
300
} else {
301
// No need to do a checkOldImpl() here, we know it's an up to date
302
// SocketImpl!
303
impl = new SocksSocketImpl();
304
}
305
if (impl != null)
306
impl.setServerSocket(this);
307
}
308
309
/**
310
* Creates the socket implementation.
311
*
312
* @throws IOException if creation fails
313
* @since 1.4
314
*/
315
void createImpl() throws SocketException {
316
if (impl == null)
317
setImpl();
318
try {
319
impl.create(true);
320
created = true;
321
} catch (IOException e) {
322
throw new SocketException(e.getMessage());
323
}
324
}
325
326
/**
327
*
328
* Binds the {@code ServerSocket} to a specific address
329
* (IP address and port number).
330
* <p>
331
* If the address is {@code null}, then the system will pick up
332
* an ephemeral port and a valid local address to bind the socket.
333
* <p>
334
* @param endpoint The IP address and port number to bind to.
335
* @throws IOException if the bind operation fails, or if the socket
336
* is already bound.
337
* @throws SecurityException if a {@code SecurityManager} is present and
338
* its {@code checkListen} method doesn't allow the operation.
339
* @throws IllegalArgumentException if endpoint is a
340
* SocketAddress subclass not supported by this socket
341
* @since 1.4
342
*/
343
public void bind(SocketAddress endpoint) throws IOException {
344
bind(endpoint, 50);
345
}
346
347
/**
348
*
349
* Binds the {@code ServerSocket} to a specific address
350
* (IP address and port number).
351
* <p>
352
* If the address is {@code null}, then the system will pick up
353
* an ephemeral port and a valid local address to bind the socket.
354
* <P>
355
* The {@code backlog} argument is the requested maximum number of
356
* pending connections on the socket. Its exact semantics are implementation
357
* specific. In particular, an implementation may impose a maximum length
358
* or may choose to ignore the parameter altogther. The value provided
359
* should be greater than {@code 0}. If it is less than or equal to
360
* {@code 0}, then an implementation specific default will be used.
361
* @param endpoint The IP address and port number to bind to.
362
* @param backlog requested maximum length of the queue of
363
* incoming connections.
364
* @throws IOException if the bind operation fails, or if the socket
365
* is already bound.
366
* @throws SecurityException if a {@code SecurityManager} is present and
367
* its {@code checkListen} method doesn't allow the operation.
368
* @throws IllegalArgumentException if endpoint is a
369
* SocketAddress subclass not supported by this socket
370
* @since 1.4
371
*/
372
public void bind(SocketAddress endpoint, int backlog) throws IOException {
373
if (isClosed())
374
throw new SocketException("Socket is closed");
375
if (!oldImpl && isBound())
376
throw new SocketException("Already bound");
377
if (endpoint == null)
378
endpoint = new InetSocketAddress(0);
379
if (!(endpoint instanceof InetSocketAddress))
380
throw new IllegalArgumentException("Unsupported address type");
381
InetSocketAddress epoint = (InetSocketAddress) endpoint;
382
if (epoint.isUnresolved())
383
throw new SocketException("Unresolved address");
384
if (backlog < 1)
385
backlog = 50;
386
try {
387
SecurityManager security = System.getSecurityManager();
388
if (security != null)
389
security.checkListen(epoint.getPort());
390
getImpl().bind(epoint.getAddress(), epoint.getPort());
391
getImpl().listen(backlog);
392
bound = true;
393
} catch(SecurityException e) {
394
bound = false;
395
throw e;
396
} catch(IOException e) {
397
bound = false;
398
throw e;
399
}
400
}
401
402
/**
403
* Returns the local address of this server socket.
404
* <p>
405
* If the socket was bound prior to being {@link #close closed},
406
* then this method will continue to return the local address
407
* after the socket is closed.
408
* <p>
409
* If there is a security manager set, its {@code checkConnect} method is
410
* called with the local address and {@code -1} as its arguments to see
411
* if the operation is allowed. If the operation is not allowed,
412
* the {@link InetAddress#getLoopbackAddress loopback} address is returned.
413
*
414
* @return the address to which this socket is bound,
415
* or the loopback address if denied by the security manager,
416
* or {@code null} if the socket is unbound.
417
*
418
* @see SecurityManager#checkConnect
419
*/
420
public InetAddress getInetAddress() {
421
if (!isBound())
422
return null;
423
try {
424
InetAddress in = getImpl().getInetAddress();
425
SecurityManager sm = System.getSecurityManager();
426
if (sm != null)
427
sm.checkConnect(in.getHostAddress(), -1);
428
return in;
429
} catch (SecurityException e) {
430
return InetAddress.getLoopbackAddress();
431
} catch (SocketException e) {
432
// nothing
433
// If we're bound, the impl has been created
434
// so we shouldn't get here
435
}
436
return null;
437
}
438
439
/**
440
* Returns the port number on which this socket is listening.
441
* <p>
442
* If the socket was bound prior to being {@link #close closed},
443
* then this method will continue to return the port number
444
* after the socket is closed.
445
*
446
* @return the port number to which this socket is listening or
447
* -1 if the socket is not bound yet.
448
*/
449
public int getLocalPort() {
450
if (!isBound())
451
return -1;
452
try {
453
return getImpl().getLocalPort();
454
} catch (SocketException e) {
455
// nothing
456
// If we're bound, the impl has been created
457
// so we shouldn't get here
458
}
459
return -1;
460
}
461
462
/**
463
* Returns the address of the endpoint this socket is bound to.
464
* <p>
465
* If the socket was bound prior to being {@link #close closed},
466
* then this method will continue to return the address of the endpoint
467
* after the socket is closed.
468
* <p>
469
* If there is a security manager set, its {@code checkConnect} method is
470
* called with the local address and {@code -1} as its arguments to see
471
* if the operation is allowed. If the operation is not allowed,
472
* a {@code SocketAddress} representing the
473
* {@link InetAddress#getLoopbackAddress loopback} address and the local
474
* port to which the socket is bound is returned.
475
*
476
* @return a {@code SocketAddress} representing the local endpoint of
477
* this socket, or a {@code SocketAddress} representing the
478
* loopback address if denied by the security manager,
479
* or {@code null} if the socket is not bound yet.
480
*
481
* @see #getInetAddress()
482
* @see #getLocalPort()
483
* @see #bind(SocketAddress)
484
* @see SecurityManager#checkConnect
485
* @since 1.4
486
*/
487
488
public SocketAddress getLocalSocketAddress() {
489
if (!isBound())
490
return null;
491
return new InetSocketAddress(getInetAddress(), getLocalPort());
492
}
493
494
/**
495
* Listens for a connection to be made to this socket and accepts
496
* it. The method blocks until a connection is made.
497
*
498
* <p>A new Socket {@code s} is created and, if there
499
* is a security manager,
500
* the security manager's {@code checkAccept} method is called
501
* with {@code s.getInetAddress().getHostAddress()} and
502
* {@code s.getPort()}
503
* as its arguments to ensure the operation is allowed.
504
* This could result in a SecurityException.
505
*
506
* @exception IOException if an I/O error occurs when waiting for a
507
* connection.
508
* @exception SecurityException if a security manager exists and its
509
* {@code checkAccept} method doesn't allow the operation.
510
* @exception SocketTimeoutException if a timeout was previously set with setSoTimeout and
511
* the timeout has been reached.
512
* @exception java.nio.channels.IllegalBlockingModeException
513
* if this socket has an associated channel, the channel is in
514
* non-blocking mode, and there is no connection ready to be
515
* accepted
516
*
517
* @return the new Socket
518
* @see SecurityManager#checkAccept
519
* @revised 1.4
520
* @spec JSR-51
521
*/
522
public Socket accept() throws IOException {
523
if (isClosed())
524
throw new SocketException("Socket is closed");
525
if (!isBound())
526
throw new SocketException("Socket is not bound yet");
527
Socket s = new Socket((SocketImpl) null);
528
implAccept(s);
529
return s;
530
}
531
532
/**
533
* Subclasses of ServerSocket use this method to override accept()
534
* to return their own subclass of socket. So a FooServerSocket
535
* will typically hand this method an <i>empty</i> FooSocket. On
536
* return from implAccept the FooSocket will be connected to a client.
537
*
538
* @param s the Socket
539
* @throws java.nio.channels.IllegalBlockingModeException
540
* if this socket has an associated channel,
541
* and the channel is in non-blocking mode
542
* @throws IOException if an I/O error occurs when waiting
543
* for a connection.
544
* @since JDK1.1
545
* @revised 1.4
546
* @spec JSR-51
547
*/
548
protected final void implAccept(Socket s) throws IOException {
549
SocketImpl si = null;
550
try {
551
if (s.impl == null)
552
s.setImpl();
553
else {
554
s.impl.reset();
555
}
556
si = s.impl;
557
s.impl = null;
558
si.address = new InetAddress();
559
si.fd = new FileDescriptor();
560
getImpl().accept(si);
561
562
SecurityManager security = System.getSecurityManager();
563
if (security != null) {
564
security.checkAccept(si.getInetAddress().getHostAddress(),
565
si.getPort());
566
}
567
} catch (IOException e) {
568
if (si != null)
569
si.reset();
570
s.impl = si;
571
throw e;
572
} catch (SecurityException e) {
573
if (si != null)
574
si.reset();
575
s.impl = si;
576
throw e;
577
}
578
s.impl = si;
579
s.postAccept();
580
}
581
582
/**
583
* Closes this socket.
584
*
585
* Any thread currently blocked in {@link #accept()} will throw
586
* a {@link SocketException}.
587
*
588
* <p> If this socket has an associated channel then the channel is closed
589
* as well.
590
*
591
* @exception IOException if an I/O error occurs when closing the socket.
592
* @revised 1.4
593
* @spec JSR-51
594
*/
595
public void close() throws IOException {
596
synchronized(closeLock) {
597
if (isClosed())
598
return;
599
if (created)
600
impl.close();
601
closed = true;
602
}
603
}
604
605
/**
606
* Returns the unique {@link java.nio.channels.ServerSocketChannel} object
607
* associated with this socket, if any.
608
*
609
* <p> A server socket will have a channel if, and only if, the channel
610
* itself was created via the {@link
611
* java.nio.channels.ServerSocketChannel#open ServerSocketChannel.open}
612
* method.
613
*
614
* @return the server-socket channel associated with this socket,
615
* or {@code null} if this socket was not created
616
* for a channel
617
*
618
* @since 1.4
619
* @spec JSR-51
620
*/
621
public ServerSocketChannel getChannel() {
622
return null;
623
}
624
625
/**
626
* Returns the binding state of the ServerSocket.
627
*
628
* @return true if the ServerSocket successfully bound to an address
629
* @since 1.4
630
*/
631
public boolean isBound() {
632
// Before 1.3 ServerSockets were always bound during creation
633
return bound || oldImpl;
634
}
635
636
/**
637
* Returns the closed state of the ServerSocket.
638
*
639
* @return true if the socket has been closed
640
* @since 1.4
641
*/
642
public boolean isClosed() {
643
synchronized(closeLock) {
644
return closed;
645
}
646
}
647
648
/**
649
* Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} with the
650
* specified timeout, in milliseconds. With this option set to a non-zero
651
* timeout, a call to accept() for this ServerSocket
652
* will block for only this amount of time. If the timeout expires,
653
* a <B>java.net.SocketTimeoutException</B> is raised, though the
654
* ServerSocket is still valid. The option <B>must</B> be enabled
655
* prior to entering the blocking operation to have effect. The
656
* timeout must be {@code > 0}.
657
* A timeout of zero is interpreted as an infinite timeout.
658
* @param timeout the specified timeout, in milliseconds
659
* @exception SocketException if there is an error in
660
* the underlying protocol, such as a TCP error.
661
* @since JDK1.1
662
* @see #getSoTimeout()
663
*/
664
public synchronized void setSoTimeout(int timeout) throws SocketException {
665
if (isClosed())
666
throw new SocketException("Socket is closed");
667
getImpl().setOption(SocketOptions.SO_TIMEOUT, new Integer(timeout));
668
}
669
670
/**
671
* Retrieve setting for {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}.
672
* 0 returns implies that the option is disabled (i.e., timeout of infinity).
673
* @return the {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT} value
674
* @exception IOException if an I/O error occurs
675
* @since JDK1.1
676
* @see #setSoTimeout(int)
677
*/
678
public synchronized int getSoTimeout() throws IOException {
679
if (isClosed())
680
throw new SocketException("Socket is closed");
681
Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT);
682
/* extra type safety */
683
if (o instanceof Integer) {
684
return ((Integer) o).intValue();
685
} else {
686
return 0;
687
}
688
}
689
690
/**
691
* Enable/disable the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
692
* socket option.
693
* <p>
694
* When a TCP connection is closed the connection may remain
695
* in a timeout state for a period of time after the connection
696
* is closed (typically known as the {@code TIME_WAIT} state
697
* or {@code 2MSL} wait state).
698
* For applications using a well known socket address or port
699
* it may not be possible to bind a socket to the required
700
* {@code SocketAddress} if there is a connection in the
701
* timeout state involving the socket address or port.
702
* <p>
703
* Enabling {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} prior to
704
* binding the socket using {@link #bind(SocketAddress)} allows the socket
705
* to be bound even though a previous connection is in a timeout state.
706
* <p>
707
* When a {@code ServerSocket} is created the initial setting
708
* of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is not defined.
709
* Applications can use {@link #getReuseAddress()} to determine the initial
710
* setting of {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}.
711
* <p>
712
* The behaviour when {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is
713
* enabled or disabled after a socket is bound (See {@link #isBound()})
714
* is not defined.
715
*
716
* @param on whether to enable or disable the socket option
717
* @exception SocketException if an error occurs enabling or
718
* disabling the {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR}
719
* socket option, or the socket is closed.
720
* @since 1.4
721
* @see #getReuseAddress()
722
* @see #bind(SocketAddress)
723
* @see #isBound()
724
* @see #isClosed()
725
*/
726
public void setReuseAddress(boolean on) throws SocketException {
727
if (isClosed())
728
throw new SocketException("Socket is closed");
729
getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on));
730
}
731
732
/**
733
* Tests if {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
734
*
735
* @return a {@code boolean} indicating whether or not
736
* {@link SocketOptions#SO_REUSEADDR SO_REUSEADDR} is enabled.
737
* @exception SocketException if there is an error
738
* in the underlying protocol, such as a TCP error.
739
* @since 1.4
740
* @see #setReuseAddress(boolean)
741
*/
742
public boolean getReuseAddress() throws SocketException {
743
if (isClosed())
744
throw new SocketException("Socket is closed");
745
return ((Boolean) (getImpl().getOption(SocketOptions.SO_REUSEADDR))).booleanValue();
746
}
747
748
/**
749
* Returns the implementation address and implementation port of
750
* this socket as a {@code String}.
751
* <p>
752
* If there is a security manager set, its {@code checkConnect} method is
753
* called with the local address and {@code -1} as its arguments to see
754
* if the operation is allowed. If the operation is not allowed,
755
* an {@code InetAddress} representing the
756
* {@link InetAddress#getLoopbackAddress loopback} address is returned as
757
* the implementation address.
758
*
759
* @return a string representation of this socket.
760
*/
761
public String toString() {
762
if (!isBound())
763
return "ServerSocket[unbound]";
764
InetAddress in;
765
if (System.getSecurityManager() != null)
766
in = InetAddress.getLoopbackAddress();
767
else
768
in = impl.getInetAddress();
769
return "ServerSocket[addr=" + in +
770
",localport=" + impl.getLocalPort() + "]";
771
}
772
773
void setBound() {
774
bound = true;
775
}
776
777
void setCreated() {
778
created = true;
779
}
780
781
/**
782
* The factory for all server sockets.
783
*/
784
private static SocketImplFactory factory = null;
785
786
/**
787
* Sets the server socket implementation factory for the
788
* application. The factory can be specified only once.
789
* <p>
790
* When an application creates a new server socket, the socket
791
* implementation factory's {@code createSocketImpl} method is
792
* called to create the actual socket implementation.
793
* <p>
794
* Passing {@code null} to the method is a no-op unless the factory
795
* was already set.
796
* <p>
797
* If there is a security manager, this method first calls
798
* the security manager's {@code checkSetFactory} method
799
* to ensure the operation is allowed.
800
* This could result in a SecurityException.
801
*
802
* @param fac the desired factory.
803
* @exception IOException if an I/O error occurs when setting the
804
* socket factory.
805
* @exception SocketException if the factory has already been defined.
806
* @exception SecurityException if a security manager exists and its
807
* {@code checkSetFactory} method doesn't allow the operation.
808
* @see java.net.SocketImplFactory#createSocketImpl()
809
* @see SecurityManager#checkSetFactory
810
*/
811
public static synchronized void setSocketFactory(SocketImplFactory fac) throws IOException {
812
if (factory != null) {
813
throw new SocketException("factory already defined");
814
}
815
SecurityManager security = System.getSecurityManager();
816
if (security != null) {
817
security.checkSetFactory();
818
}
819
factory = fac;
820
}
821
822
/**
823
* Sets a default proposed value for the
824
* {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option for sockets
825
* accepted from this {@code ServerSocket}. The value actually set
826
* in the accepted socket must be determined by calling
827
* {@link Socket#getReceiveBufferSize()} after the socket
828
* is returned by {@link #accept()}.
829
* <p>
830
* The value of {@link SocketOptions#SO_RCVBUF SO_RCVBUF} is used both to
831
* set the size of the internal socket receive buffer, and to set the size
832
* of the TCP receive window that is advertized to the remote peer.
833
* <p>
834
* It is possible to change the value subsequently, by calling
835
* {@link Socket#setReceiveBufferSize(int)}. However, if the application
836
* wishes to allow a receive window larger than 64K bytes, as defined by RFC1323
837
* then the proposed value must be set in the ServerSocket <B>before</B>
838
* it is bound to a local address. This implies, that the ServerSocket must be
839
* created with the no-argument constructor, then setReceiveBufferSize() must
840
* be called and lastly the ServerSocket is bound to an address by calling bind().
841
* <p>
842
* Failure to do this will not cause an error, and the buffer size may be set to the
843
* requested value but the TCP receive window in sockets accepted from
844
* this ServerSocket will be no larger than 64K bytes.
845
*
846
* @exception SocketException if there is an error
847
* in the underlying protocol, such as a TCP error.
848
*
849
* @param size the size to which to set the receive buffer
850
* size. This value must be greater than 0.
851
*
852
* @exception IllegalArgumentException if the
853
* value is 0 or is negative.
854
*
855
* @since 1.4
856
* @see #getReceiveBufferSize
857
*/
858
public synchronized void setReceiveBufferSize (int size) throws SocketException {
859
if (!(size > 0)) {
860
throw new IllegalArgumentException("negative receive size");
861
}
862
if (isClosed())
863
throw new SocketException("Socket is closed");
864
getImpl().setOption(SocketOptions.SO_RCVBUF, new Integer(size));
865
}
866
867
/**
868
* Gets the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF} option
869
* for this {@code ServerSocket}, that is the proposed buffer size that
870
* will be used for Sockets accepted from this {@code ServerSocket}.
871
*
872
* <p>Note, the value actually set in the accepted socket is determined by
873
* calling {@link Socket#getReceiveBufferSize()}.
874
* @return the value of the {@link SocketOptions#SO_RCVBUF SO_RCVBUF}
875
* option for this {@code Socket}.
876
* @exception SocketException if there is an error
877
* in the underlying protocol, such as a TCP error.
878
* @see #setReceiveBufferSize(int)
879
* @since 1.4
880
*/
881
public synchronized int getReceiveBufferSize()
882
throws SocketException{
883
if (isClosed())
884
throw new SocketException("Socket is closed");
885
int result = 0;
886
Object o = getImpl().getOption(SocketOptions.SO_RCVBUF);
887
if (o instanceof Integer) {
888
result = ((Integer)o).intValue();
889
}
890
return result;
891
}
892
893
/**
894
* Sets performance preferences for this ServerSocket.
895
*
896
* <p> Sockets use the TCP/IP protocol by default. Some implementations
897
* may offer alternative protocols which have different performance
898
* characteristics than TCP/IP. This method allows the application to
899
* express its own preferences as to how these tradeoffs should be made
900
* when the implementation chooses from the available protocols.
901
*
902
* <p> Performance preferences are described by three integers
903
* whose values indicate the relative importance of short connection time,
904
* low latency, and high bandwidth. The absolute values of the integers
905
* are irrelevant; in order to choose a protocol the values are simply
906
* compared, with larger values indicating stronger preferences. If the
907
* application prefers short connection time over both low latency and high
908
* bandwidth, for example, then it could invoke this method with the values
909
* {@code (1, 0, 0)}. If the application prefers high bandwidth above low
910
* latency, and low latency above short connection time, then it could
911
* invoke this method with the values {@code (0, 1, 2)}.
912
*
913
* <p> Invoking this method after this socket has been bound
914
* will have no effect. This implies that in order to use this capability
915
* requires the socket to be created with the no-argument constructor.
916
*
917
* @param connectionTime
918
* An {@code int} expressing the relative importance of a short
919
* connection time
920
*
921
* @param latency
922
* An {@code int} expressing the relative importance of low
923
* latency
924
*
925
* @param bandwidth
926
* An {@code int} expressing the relative importance of high
927
* bandwidth
928
*
929
* @since 1.5
930
*/
931
public void setPerformancePreferences(int connectionTime,
932
int latency,
933
int bandwidth)
934
{
935
/* Not implemented yet */
936
}
937
938
}
939
940