下面列出了怎么用java.net.SocketException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns a list of {@link NetworkData}.
*
* This method iterates over all the network interfaces to return those that
* are up and running.
*
* NOTE: it may be VERY EXPENSIVE on Windows systems, because that OS
* creates a lot of virtual network interfaces.
*
* @return a list of {@link NetworkData}
*/
public static List<NetworkData> getNetworkDataList() {
try {
InetAddress inetAddress = InetAddress.getLocalHost();
List<NetworkInterface> networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
HashSet<NetworkData> networkDataHashSet = new HashSet<>();
for (NetworkInterface networkInterface : networkInterfaces) {
NetworkData networkData = buildNetworkData(networkInterface, inetAddress);
if (networkData != null) {
networkDataHashSet.add(networkData);
}
}
return new ArrayList<>(networkDataHashSet);
} catch (SocketException | NullPointerException | UnknownHostException e) {
return Collections.emptyList();
}
}
/**
* The following method, createSocket, is defined in NetworkClient
* and overridden here so that the socket facroty is used to create
* new sockets.
*/
@Override
protected Socket createSocket() throws IOException {
try {
return sslSocketFactory.createSocket();
} catch (SocketException se) {
//
// bug 6771432
// javax.net.SocketFactory throws a SocketException with an
// UnsupportedOperationException as its cause to indicate that
// unconnected sockets have not been implemented.
//
Throwable t = se.getCause();
if (t != null && t instanceof UnsupportedOperationException) {
return super.createSocket();
} else {
throw se;
}
}
}
private boolean populateNonce() {
try {
transaction.updateNonce();
return true;
} catch (final RuntimeException e) {
LOG.warn("Unable to get nonce from web3j provider.", e);
final Throwable cause = e.getCause();
if (cause instanceof SocketException
|| cause instanceof SocketTimeoutException
|| cause instanceof TimeoutException) {
routingContext.fail(
GATEWAY_TIMEOUT.code(), new JsonRpcException(CONNECTION_TO_DOWNSTREAM_NODE_TIMED_OUT));
} else if (cause instanceof SSLHandshakeException) {
routingContext.fail(BAD_GATEWAY.code(), cause);
} else {
routingContext.fail(GATEWAY_TIMEOUT.code(), new JsonRpcException(INTERNAL_ERROR));
}
} catch (final Throwable thrown) {
LOG.debug("Failed to encode/serialize transaction: {}", transaction, thrown);
routingContext.fail(BAD_REQUEST.code(), new JsonRpcException(INTERNAL_ERROR));
}
return false;
}
public void setProperties(Socket socket) throws SocketException{
if (rxBufSize != null)
socket.setReceiveBufferSize(rxBufSize.intValue());
if (txBufSize != null)
socket.setSendBufferSize(txBufSize.intValue());
if (ooBInline !=null)
socket.setOOBInline(ooBInline.booleanValue());
if (soKeepAlive != null)
socket.setKeepAlive(soKeepAlive.booleanValue());
if (performanceConnectionTime != null && performanceLatency != null &&
performanceBandwidth != null)
socket.setPerformancePreferences(
performanceConnectionTime.intValue(),
performanceLatency.intValue(),
performanceBandwidth.intValue());
if (soReuseAddress != null)
socket.setReuseAddress(soReuseAddress.booleanValue());
if (soLingerOn != null && soLingerTime != null)
socket.setSoLinger(soLingerOn.booleanValue(),
soLingerTime.intValue());
if (soTimeout != null && soTimeout.intValue() >= 0)
socket.setSoTimeout(soTimeout.intValue());
if (tcpNoDelay != null)
socket.setTcpNoDelay(tcpNoDelay.booleanValue());
}
@Override
public void receive(DatagramPacket p) throws IOException {
// get temporary direct buffer with a capacity of p.bufLength
int bufLength = DatagramPackets.getBufLength(p);
ByteBuffer bb = Util.getTemporaryDirectBuffer(bufLength);
try {
long nanos = MILLISECONDS.toNanos(timeout);
SocketAddress sender = dc.blockingReceive(bb, nanos);
bb.flip();
synchronized (p) {
// copy bytes to the DatagramPacket and set length
int len = Math.min(bb.limit(), DatagramPackets.getBufLength(p));
bb.get(p.getData(), p.getOffset(), len);
DatagramPackets.setLength(p, len);
// sender address
p.setSocketAddress(sender);
}
} catch (ClosedChannelException e) {
var exc = new SocketException("Socket closed");
exc.initCause(e);
throw exc;
} finally {
Util.offerFirstTemporaryDirectBuffer(bb);
}
}
/**
* The following method, createSocket, is defined in NetworkClient
* and overridden here so that the socket facroty is used to create
* new sockets.
*/
@Override
protected Socket createSocket() throws IOException {
try {
return sslSocketFactory.createSocket();
} catch (SocketException se) {
//
// bug 6771432
// javax.net.SocketFactory throws a SocketException with an
// UnsupportedOperationException as its cause to indicate that
// unconnected sockets have not been implemented.
//
Throwable t = se.getCause();
if (t != null && t instanceof UnsupportedOperationException) {
return super.createSocket();
} else {
throw se;
}
}
}
/**
* Returns a list of all the addresses on the system.
* @param inclLoopback
* if {@code true}, include the loopback addresses
* @param ipv4Only
* it {@code true}, only IPv4 addresses will be included
*/
static List<InetAddress> getAddresses(boolean inclLoopback,
boolean ipv4Only)
throws SocketException {
ArrayList<InetAddress> list = new ArrayList<InetAddress>();
Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netInf : Collections.list(nets)) {
Enumeration<InetAddress> addrs = netInf.getInetAddresses();
for (InetAddress addr : Collections.list(addrs)) {
if (!list.contains(addr) &&
(inclLoopback ? true : !addr.isLoopbackAddress()) &&
(ipv4Only ? (addr instanceof Inet4Address) : true)) {
list.add(addr);
}
}
}
return list;
}
public String getLocalIpAddresses() {
ArrayList<String> addresses = new ArrayList<String>();
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
addresses.add(inetAddress.getHostAddress().toString());
}
}
}
} catch (SocketException ex) {
Log.e(THIS_FILE, "Impossible to get ip address", ex);
}
return TextUtils.join("\n", addresses);
}
public static String getPhoneIp(Context application) {
WifiManager wifiManager = (WifiManager) application.getSystemService("wifi");
if (wifiManager.isWifiEnabled()) {
return intToIp(wifiManager.getConnectionInfo().getIpAddress());
}
try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
Enumeration<InetAddress> enumIpAddr = ((NetworkInterface) en.nextElement()).getInetAddresses();
while (enumIpAddr.hasMoreElements()) {
InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
/**
* On systems with multiple network interfaces and mixed IPv6/IPv4 get a valid network
* interface for binding to multicast
*
* @return a network interface suitable for multicast
* @throws SocketException if a problem occurs while reading the network interfaces
*/
public static NetworkInterface getMulticastNetworkInterface() throws SocketException
{
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements())
{
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> addressesFromNetworkInterface = networkInterface.getInetAddresses();
while (addressesFromNetworkInterface.hasMoreElements())
{
InetAddress inetAddress = addressesFromNetworkInterface.nextElement();
if (inetAddress.isSiteLocalAddress()
&& !inetAddress.isAnyLocalAddress()
&& !inetAddress.isLinkLocalAddress()
&& !inetAddress.isLoopbackAddress()
&& !inetAddress.isMulticastAddress())
{
return networkInterface;
}
}
}
return null;
}
/**
* Layer SSL traffic over an existing connection, rather than
* creating a new connection.
*
* The existing connection may be used only for SSL traffic (using this
* SSLSocket) until the SSLSocket.close() call returns. However, if a
* protocol error is detected, that existing connection is automatically
* closed.
* <p>
* This particular constructor always uses the socket in the
* role of an SSL client. It may be useful in cases which start
* using SSL after some initial data transfers, for example in some
* SSL tunneling applications or as part of some kinds of application
* protocols which negotiate use of a SSL based security.
*/
SSLSocketImpl(SSLContextImpl sslContext, Socket sock,
String peerHost, int port, boolean autoClose) throws IOException {
super(sock);
// We always layer over a connected socket
if (!sock.isConnected()) {
throw new SocketException("Underlying socket is not connected");
}
this.sslContext = sslContext;
HandshakeHash handshakeHash = new HandshakeHash();
this.conContext = new TransportContext(sslContext, this,
new SSLSocketInputRecord(handshakeHash),
new SSLSocketOutputRecord(handshakeHash), true);
this.peerHost = peerHost;
this.autoClose = autoClose;
doneConnect();
}
/**
* Load folder in a separate thread.
*
* @param folder current folder
* @param outputStream client connection
* @throws InterruptedException on error
* @throws IOException on error
*/
public static void loadFolder(ExchangeSession.Folder folder, OutputStream outputStream) throws InterruptedException, IOException {
FolderLoadThread folderLoadThread = new FolderLoadThread(currentThread().getName(), folder);
folderLoadThread.start();
while (!folderLoadThread.isComplete) {
folderLoadThread.join(20000);
LOGGER.debug("Still loading " + folder.folderPath + " (" + folder.count() + " messages)");
if (Settings.getBooleanProperty("davmail.enableKeepAlive", false)) {
try {
outputStream.write(' ');
outputStream.flush();
} catch (SocketException e) {
folderLoadThread.interrupt();
throw e;
}
}
}
if (folderLoadThread.exception != null) {
throw folderLoadThread.exception;
}
}
public static String getMask(String intf){
try {
NetworkInterface ntwrk = NetworkInterface.getByName(intf);
Iterator<InterfaceAddress> addrList = ntwrk.getInterfaceAddresses().iterator();
while (addrList.hasNext()) {
InterfaceAddress addr = addrList.next();
InetAddress ip = addr.getAddress();
if (ip instanceof Inet4Address) {
String mask = ip.getHostAddress() + "/" +
addr.getNetworkPrefixLength();
return mask;
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return null;
}
@Test
public void testOutputStreamClosed() throws Exception {
LogMessageAccumulator logMessages = new LogMessageAccumulator();
try {
logMessages.registerTo(RemoteEndpoint.class);
TestEndpoint endp = new TestEndpoint();
MessageConsumer consumer = new MessageConsumer() {
@Override
public void consume(Message message) throws JsonRpcException {
throw new JsonRpcException(new SocketException("Socket closed"));
}
};
RemoteEndpoint endpoint = new RemoteEndpoint(consumer, endp);
endpoint.notify("foo", null);
logMessages.await(Level.INFO, "Failed to send notification message.");
} finally {
logMessages.unregister();
}
}
/**
* 获取可用的端口号
*/
public void getMyUsefulPort()
{
while(true)
{
try
{
// 实例化一个DatagramSocket
socket = new DatagramSocket(myPort);
break;
}
catch (SocketException e)
{
myPort++;
}
}
}
private static String getLinuxLocalIP() {
String ip = "";
try {
Enumeration<NetworkInterface> e1 = (Enumeration<NetworkInterface>) NetworkInterface.getNetworkInterfaces();
while (e1.hasMoreElements()) {
NetworkInterface ni = e1.nextElement();
if (netWorkCard.equals(ni.getName()) || NETWORK_CARD.equals(ni.getName())
|| NETWORK_CARD_BAND.equals(ni.getName())) {
Enumeration<InetAddress> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress ia = e2.nextElement();
if (ia instanceof Inet6Address) {
continue;
}
ip = ia.getHostAddress();
}
break;
} else {
continue;
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return ip;
}
/**
* Send a DESCRIBE Message.
*
* Call describe(MAX_RETRY = 5)
*
* @return
* @throws SocketException
*/
public String describe() throws SocketException
{
String desc = null;
try {
desc = describe(3);
} catch (RuntimeException rex) {
if( desc == null ){
//single retry
desc = describe(3);
}
}
return desc;
}
/**
* Returns host address that can be targeted from the outside, like from a
* test hub.
*
* @return host address
* @throws RuntimeException
* if host name could not be determined or
* {@link SocketException} was caught during the determination.
*/
protected String getCurrentHostAddress() {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface
.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface nwInterface = interfaces.nextElement();
if (!nwInterface.isUp() || nwInterface.isLoopback()
|| nwInterface.isVirtual()) {
continue;
}
Optional<String> address = getHostAddress(nwInterface);
if (address.isPresent()) {
return address.get();
}
}
} catch (SocketException e) {
throw new RuntimeException("Could not find the host name", e);
}
throw new RuntimeException(
"No compatible (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) ip address found.");
}
/**
* get ipv4 address of first matching network interface in the given list
* network interface can not be loop back and it has to be up
* @param interfaceNames
* @return
*/
public static String getLocalIPFromNetworkInterfaces(List<String> interfaceNames) {
try {
for (String nwInterfaceName: interfaceNames) {
NetworkInterface networkInterface = NetworkInterface.getByName(nwInterfaceName);
if (networkInterface != null
&& !networkInterface.isLoopback()
&& networkInterface.isUp()) {
List<InterfaceAddress> addressList = networkInterface.getInterfaceAddresses();
for (InterfaceAddress adress: addressList) {
if (isValidIPv4(adress.getAddress().getHostAddress())) {
return adress.getAddress().getHostAddress();
}
}
}
}
} catch (SocketException e) {
LOG.log(Level.SEVERE, "Error retrieving network interface list", e);
}
return null;
}
@Override
public Set<SocketAddress> getRemoteAddresses()
throws IOException {
synchronized (stateLock) {
if (!isOpen())
throw new ClosedChannelException();
if (!isConnected() || isShutdown)
return Collections.emptySet();
try {
return SctpNet.getRemoteAddresses(fdVal, 0/*unused*/);
} catch (SocketException unused) {
/* an open connected channel should always have remote addresses */
return remoteAddresses;
}
}
}
/**
* Get local Ip address.
*/
public static InetAddress getLocalIPAddress() {
Enumeration<NetworkInterface> enumeration = null;
try {
enumeration = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
if (enumeration != null) {
while (enumeration.hasMoreElements()) {
NetworkInterface nif = enumeration.nextElement();
Enumeration<InetAddress> inetAddresses = nif.getInetAddresses();
if (inetAddresses != null) {
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
if (!inetAddress.isLoopbackAddress() && isIPv4Address(inetAddress.getHostAddress())) {
return inetAddress;
}
}
}
}
}
return null;
}
public static void beforeUdpCreate() throws SocketException {
if (System.getSecurityManager() != null) {
if (numSockets.incrementAndGet() > maxSockets) {
numSockets.decrementAndGet();
throw new SocketException("maximum number of DatagramSockets reached");
}
}
}
protected void write(ByteBuffer buffer) throws IOException {
while (buffer.hasRemaining()) {
int written = channel().write(buffer);
if (written < 0 || !isConnected()) {
// indicator the socket was closed
Closer.close(channel());
throw new SocketException("Cannot write buffer to channel");
}
}
}
/**
* Manages refreshing the forests and hosts and retrying events after a host
* becomes unavailable.
* @param moveMgr the DataMovementManager (used to call readForestConfig to reset after black-listing an unavailable host)
*/
public HostAvailabilityListener(DataMovementManager moveMgr) {
if (moveMgr == null) throw new IllegalArgumentException("moveMgr must not be null");
this.moveMgr = moveMgr;
if (moveMgr.getConnectionType() == DatabaseClient.ConnectionType.DIRECT) {
hostUnavailableExceptions.add(SocketException.class);
hostUnavailableExceptions.add(SSLException.class);
hostUnavailableExceptions.add(UnknownHostException.class);
}
}
/**
* @see com.mysql.jdbc.SocketFactory#connect(String, Properties)
*/
public Socket connect(String host, int portNumber /* ignored */, Properties props) throws SocketException, IOException {
String namedPipePath = props.getProperty(NAMED_PIPE_PROP_NAME);
if (namedPipePath == null) {
namedPipePath = "\\\\.\\pipe\\MySQL";
} else if (namedPipePath.length() == 0) {
throw new SocketException(Messages.getString("NamedPipeSocketFactory.2") + NAMED_PIPE_PROP_NAME + Messages.getString("NamedPipeSocketFactory.3"));
}
this.namedPipeSocket = new NamedPipeSocket(namedPipePath);
return this.namedPipeSocket;
}
@Override
protected TSocket acceptImpl() throws TTransportException {
TSocket ts = super.acceptImpl();
try {
ts.getSocket().setKeepAlive(true);
} catch (SocketException e) {
throw new TTransportException(e);
}
return ts;
}
private void setTimeout(int milliseconds) throws SQLException {
// input and output protocol are identical in our usage
TTransport socket = this.clientService.getInputProtocol().getTransport();
if (socket instanceof SocketTimeout) {
try {
((SocketTimeout)socket).setSoTimeout(milliseconds);
} catch (SocketException se) {
throw ThriftExceptionUtil.newSQLException(SQLState.SOCKET_EXCEPTION,
se, se.getMessage());
}
}
}
/**
* Open informSocket if it's not already done.
*/
synchronized void openInformSocketIfNeeded() throws SocketException {
if (informSession == null) {
informSession = new SnmpSession(this) ;
if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) {
SNMP_ADAPTOR_LOGGER.logp(Level.FINER, dbgTag,
"openInformSocketIfNeeded",
"to send inform requests and receive inform responses");
}
}
}
/**
* Accepts incoming connections and handles then with
* <tt>TCPConnectionHandler</tt> instances.
*/
@Override
public void run() {
try {
/*
* A server socket is opened with a connectivity queue of a size specified
* in int floodProtection. Concurrent login handling under normal circumstances
* should be allright, denial of service attacks via massive parallel
* program logins can probably be prevented.
*/
m_ServerSocket = new ServerSocket(m_Port, m_FloodProtection, m_Address);
logger.debug("Listenening to {} (Port {})", m_ServerSocket.toString(), m_Port);
// Infinite loop, taking care of resources in case of a lot of parallel logins
do {
Socket incoming = m_ServerSocket.accept();
logger.debug("Making new connection {}", incoming.toString());
if (m_Listening) {
// FIXME: Replace with object pool due to resource issues
m_ThreadPool.execute(new TCPConnectionHandler(m_ConnectionFactory.create(incoming)));
count();
} else {
// just close the socket
incoming.close();
}
} while (m_Listening);
} catch (SocketException iex) {
if (!m_Listening) {
return;
} else {
iex.printStackTrace();
}
} catch (IOException e) {
// FIXME: this is a major failure, how do we handle this
}
}
@Override
public boolean isOobInline() {
try {
return getSocket().getOOBInline();
} catch (SocketException e) {
throw new RuntimeException(e);
}
}