use of java.net.SocketException in project jetty.project by eclipse.
the class IOTest method testHalfClose.
@Test
public void testHalfClose() throws Exception {
ServerSocket connector = new ServerSocket(0);
Socket client = new Socket("localhost", connector.getLocalPort());
Socket server = connector.accept();
// we can write both ways
client.getOutputStream().write(1);
assertEquals(1, server.getInputStream().read());
server.getOutputStream().write(1);
assertEquals(1, client.getInputStream().read());
// shutdown output results in read -1
client.shutdownOutput();
assertEquals(-1, server.getInputStream().read());
// Even though EOF has been read, the server input is not seen as shutdown
assertFalse(server.isInputShutdown());
// and we can read -1 again
assertEquals(-1, server.getInputStream().read());
// but cannot write
try {
client.getOutputStream().write(1);
fail("exception expected");
} catch (SocketException e) {
}
// but can still write in opposite direction.
server.getOutputStream().write(1);
assertEquals(1, client.getInputStream().read());
// server can shutdown input to match the shutdown out of client
server.shutdownInput();
// now we EOF instead of reading -1
try {
server.getInputStream().read();
fail("exception expected");
} catch (SocketException e) {
}
// but can still write in opposite direction.
server.getOutputStream().write(1);
assertEquals(1, client.getInputStream().read());
// client can shutdown input
client.shutdownInput();
// now we EOF instead of reading -1
try {
client.getInputStream().read();
fail("exception expected");
} catch (SocketException e) {
}
// But we can still write at the server (data which will never be read)
server.getOutputStream().write(1);
// and the server output is not shutdown
assertFalse(server.isOutputShutdown());
// until we explictly shut it down
server.shutdownOutput();
// and now we can't write
try {
server.getOutputStream().write(1);
fail("exception expected");
} catch (SocketException e) {
}
// but the sockets are still open
assertFalse(client.isClosed());
assertFalse(server.isClosed());
// but if we close one end
client.close();
// it is seen as closed.
assertTrue(client.isClosed());
// but not the other end
assertFalse(server.isClosed());
// which has to be closed explictly
server.close();
assertTrue(server.isClosed());
}
use of java.net.SocketException in project jetty.project by eclipse.
the class IOTest method testHalfCloseClientServer.
@Test
public void testHalfCloseClientServer() throws Exception {
ServerSocketChannel connector = ServerSocketChannel.open();
connector.socket().bind(null);
Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket();
client.setSoTimeout(1000);
client.setSoLinger(false, -1);
Socket server = connector.accept().socket();
server.setSoTimeout(1000);
server.setSoLinger(false, -1);
// Write from client to server
client.getOutputStream().write(1);
// Server reads
assertEquals(1, server.getInputStream().read());
// Write from server to client with oshut
server.getOutputStream().write(1);
// System.err.println("OSHUT "+server);
server.shutdownOutput();
// Client reads response
assertEquals(1, client.getInputStream().read());
try {
// Client reads -1 and does ishut
assertEquals(-1, client.getInputStream().read());
assertFalse(client.isInputShutdown());
//System.err.println("ISHUT "+client);
client.shutdownInput();
// Client ???
//System.err.println("OSHUT "+client);
client.shutdownOutput();
//System.err.println("CLOSE "+client);
client.close();
// Server reads -1, does ishut and then close
assertEquals(-1, server.getInputStream().read());
assertFalse(server.isInputShutdown());
try {
server.shutdownInput();
} catch (SocketException e) {
// System.err.println(e);
}
//System.err.println("CLOSE "+server);
server.close();
} catch (Exception e) {
System.err.println(e);
assertTrue(OS.IS_OSX);
}
}
use of java.net.SocketException in project jetty.project by eclipse.
the class SSLEngineTest method testRequestJettyHttps.
@Test
public void testRequestJettyHttps() throws Exception {
server.setHandler(new HelloWorldHandler());
server.start();
final int loops = 10;
final int numConns = 20;
Socket[] client = new Socket[numConns];
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
ctx.init(null, SslContextFactory.TRUST_ALL_CERTS, new java.security.SecureRandom());
int port = connector.getLocalPort();
try {
for (int l = 0; l < loops; l++) {
// System.err.print('.');
try {
for (int i = 0; i < numConns; ++i) {
// System.err.println("write:"+i);
client[i] = ctx.getSocketFactory().createSocket("localhost", port);
OutputStream os = client[i].getOutputStream();
os.write(REQUEST0.getBytes());
os.write(REQUEST0.getBytes());
os.flush();
}
for (int i = 0; i < numConns; ++i) {
// System.err.println("flush:"+i);
OutputStream os = client[i].getOutputStream();
os.write(REQUEST1.getBytes());
os.flush();
}
for (int i = 0; i < numConns; ++i) {
// System.err.println("read:"+i);
// Read the response.
String responses = readResponse(client[i]);
// Check the responses
assertEquals(String.format("responses loop=%d connection=%d", l, i), RESPONSE0 + RESPONSE0 + RESPONSE1, responses);
}
} finally {
for (int i = 0; i < numConns; ++i) {
if (client[i] != null) {
try {
assertEquals(-1, client[i].getInputStream().read());
} catch (SocketException e) {
}
}
}
}
}
} finally {
// System.err.println();
}
}
use of java.net.SocketException in project jetty.project by eclipse.
the class ConnectorTimeoutTest method testMaxIdleWithRequest10NoClientClose.
@Test(timeout = 60000)
public void testMaxIdleWithRequest10NoClientClose() throws Exception {
final Exchanger<EndPoint> exchanger = new Exchanger<>();
configureServer(new HelloWorldHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
try {
exchanger.exchange(baseRequest.getHttpChannel().getEndPoint());
} catch (Exception e) {
e.printStackTrace();
}
super.handle(target, baseRequest, request, response);
}
});
Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
client.setSoTimeout(10000);
Assert.assertFalse(client.isClosed());
OutputStream os = client.getOutputStream();
InputStream is = client.getInputStream();
os.write(("GET / HTTP/1.0\r\n" + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + "connection: close\r\n" + "\r\n").getBytes("utf-8"));
os.flush();
// Get the server side endpoint
EndPoint endPoint = exchanger.exchange(null, 10, TimeUnit.SECONDS);
if (endPoint instanceof SslConnection.DecryptedEndPoint)
endPoint = endPoint.getConnection().getEndPoint();
// read the response
String result = IO.toString(is);
Assert.assertThat("OK", result, Matchers.containsString("200 OK"));
// check client reads EOF
Assert.assertEquals(-1, is.read());
// wait for idle timeout
TimeUnit.MILLISECONDS.sleep(3 * MAX_IDLE_TIME);
// further writes will get broken pipe or similar
try {
for (int i = 0; i < 1000; i++) {
os.write(("GET / HTTP/1.0\r\n" + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + "connection: keep-alive\r\n" + "\r\n").getBytes("utf-8"));
os.flush();
}
Assert.fail("half close should have timed out");
} catch (SocketException e) {
// expected
}
// check the server side is closed
Assert.assertFalse(endPoint.isOpen());
}
use of java.net.SocketException in project zookeeper by apache.
the class LeaderElection method lookForLeader.
/**
* Invoked in QuorumPeer to find or elect a new leader.
*
* @throws InterruptedException
*/
public Vote lookForLeader() throws InterruptedException {
try {
self.jmxLeaderElectionBean = new LeaderElectionBean();
MBeanRegistry.getInstance().register(self.jmxLeaderElectionBean, self.jmxLocalPeerBean);
} catch (Exception e) {
LOG.warn("Failed to register with JMX", e);
self.jmxLeaderElectionBean = null;
}
try {
self.setCurrentVote(new Vote(self.getId(), self.getLastLoggedZxid()));
// We are going to look for a leader by casting a vote for ourself
byte[] requestBytes = new byte[4];
ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes);
byte[] responseBytes = new byte[28];
ByteBuffer responseBuffer = ByteBuffer.wrap(responseBytes);
/* The current vote for the leader. Initially me! */
DatagramSocket s = null;
try {
s = new DatagramSocket();
s.setSoTimeout(200);
} catch (SocketException e1) {
LOG.error("Socket exception when creating socket for leader election", e1);
System.exit(4);
}
DatagramPacket requestPacket = new DatagramPacket(requestBytes, requestBytes.length);
DatagramPacket responsePacket = new DatagramPacket(responseBytes, responseBytes.length);
int xid = epochGen.nextInt();
while (self.isRunning()) {
HashMap<InetSocketAddress, Vote> votes = new HashMap<InetSocketAddress, Vote>(self.getVotingView().size());
requestBuffer.clear();
requestBuffer.putInt(xid);
requestPacket.setLength(4);
HashSet<Long> heardFrom = new HashSet<Long>();
for (QuorumServer server : self.getVotingView().values()) {
LOG.info("Server address: " + server.addr);
try {
requestPacket.setSocketAddress(server.addr);
} catch (IllegalArgumentException e) {
// in order to capture this critical detail.
throw new IllegalArgumentException("Unable to set socket address on packet, msg:" + e.getMessage() + " with addr:" + server.addr, e);
}
try {
s.send(requestPacket);
responsePacket.setLength(responseBytes.length);
s.receive(responsePacket);
if (responsePacket.getLength() != responseBytes.length) {
LOG.error("Got a short response: " + responsePacket.getLength());
continue;
}
responseBuffer.clear();
int recvedXid = responseBuffer.getInt();
if (recvedXid != xid) {
LOG.error("Got bad xid: expected " + xid + " got " + recvedXid);
continue;
}
long peerId = responseBuffer.getLong();
heardFrom.add(peerId);
//if(server.id != peerId){
Vote vote = new Vote(responseBuffer.getLong(), responseBuffer.getLong());
InetSocketAddress addr = (InetSocketAddress) responsePacket.getSocketAddress();
votes.put(addr, vote);
//}
} catch (IOException e) {
LOG.warn("Ignoring exception while looking for leader", e);
// Errors are okay, since hosts may be
// down
}
}
ElectionResult result = countVotes(votes, heardFrom);
// for a dead peer
if (result.numValidVotes == 0) {
self.setCurrentVote(new Vote(self.getId(), self.getLastLoggedZxid()));
} else {
if (result.winner.getId() >= 0) {
self.setCurrentVote(result.vote);
// To do: this doesn't use a quorum verifier
if (result.winningCount > (self.getVotingView().size() / 2)) {
self.setCurrentVote(result.winner);
s.close();
Vote current = self.getCurrentVote();
LOG.info("Found leader: my type is: " + self.getLearnerType());
/*
* We want to make sure we implement the state machine
* correctly. If we are a PARTICIPANT, once a leader
* is elected we can move either to LEADING or
* FOLLOWING. However if we are an OBSERVER, it is an
* error to be elected as a Leader.
*/
if (self.getLearnerType() == LearnerType.OBSERVER) {
if (current.getId() == self.getId()) {
// This should never happen!
LOG.error("OBSERVER elected as leader!");
Thread.sleep(100);
} else {
self.setPeerState(ServerState.OBSERVING);
Thread.sleep(100);
return current;
}
} else {
self.setPeerState((current.getId() == self.getId()) ? ServerState.LEADING : ServerState.FOLLOWING);
if (self.getPeerState() == ServerState.FOLLOWING) {
Thread.sleep(100);
}
return current;
}
}
}
}
Thread.sleep(1000);
}
return null;
} finally {
try {
if (self.jmxLeaderElectionBean != null) {
MBeanRegistry.getInstance().unregister(self.jmxLeaderElectionBean);
}
} catch (Exception e) {
LOG.warn("Failed to unregister with JMX", e);
}
self.jmxLeaderElectionBean = null;
}
}
Aggregations