use of java.net.SocketAddress in project jetty.project by eclipse.
the class SelectorManager method chooseSelector.
private ManagedSelector chooseSelector(SelectableChannel channel) {
// Ideally we would like to have all connections from the same client end
// up on the same selector (to try to avoid smearing the data from a single
// client over all cores), but because of proxies, the remote address may not
// really be the client - so we have to hedge our bets to ensure that all
// channels don't end up on the one selector for a proxy.
ManagedSelector candidate1 = null;
if (channel != null) {
try {
if (channel instanceof SocketChannel) {
SocketAddress remote = ((SocketChannel) channel).getRemoteAddress();
if (remote instanceof InetSocketAddress) {
byte[] addr = ((InetSocketAddress) remote).getAddress().getAddress();
if (addr != null) {
int s = addr[addr.length - 1] & 0xFF;
candidate1 = _selectors[s % getSelectorCount()];
}
}
}
} catch (IOException x) {
LOG.ignore(x);
}
}
// The ++ increment here is not atomic, but it does not matter,
// so long as the value changes sometimes, then connections will
// be distributed over the available selectors.
long s = _selectorIndex++;
int index = (int) (s % getSelectorCount());
ManagedSelector candidate2 = _selectors[index];
if (candidate1 == null || candidate1.size() >= candidate2.size() * 2)
return candidate2;
return candidate1;
}
use of java.net.SocketAddress in project jetty.project by eclipse.
the class BadRequestLogHandlerTest method testLogHandler.
@Test(timeout = 4000)
public void testLogHandler() throws Exception {
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(0);
server.setConnectors(new Connector[] { connector });
CaptureLog captureLog = new CaptureLog();
RequestLogHandler requestLog = new RequestLogHandler();
requestLog.setRequestLog(captureLog);
requestLog.setHandler(new HelloHandler());
server.setHandler(requestLog);
try {
server.start();
String host = connector.getHost();
if (host == null) {
host = "localhost";
}
InetAddress destAddr = InetAddress.getByName(host);
int port = connector.getLocalPort();
SocketAddress endpoint = new InetSocketAddress(destAddr, port);
Socket socket = new Socket();
socket.setSoTimeout(1000);
socket.connect(endpoint);
try (OutputStream out = socket.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
InputStream in = socket.getInputStream();
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
StringReader request = new StringReader(requestHeader);
IO.copy(request, writer);
writer.flush();
StringWriter response = new StringWriter();
IO.copy(reader, response);
LOG.info("Response: {}", response);
} finally {
socket.close();
}
assertRequestLog(captureLog);
} finally {
server.stop();
}
}
use of java.net.SocketAddress in project jetty.project by eclipse.
the class BlockheadClient method connect.
/* (non-Javadoc)
* @see org.eclipse.jetty.websocket.common.test.IBlockheadClient#connect()
*/
@Override
public void connect() throws IOException {
InetAddress destAddr = InetAddress.getByName(destHttpURI.getHost());
int port = destHttpURI.getPort();
SocketAddress endpoint = new InetSocketAddress(destAddr, port);
socket = new Socket();
socket.setSoTimeout(timeout);
socket.connect(endpoint);
out = socket.getOutputStream();
in = socket.getInputStream();
}
use of java.net.SocketAddress in project tomcat by apache.
the class TestHttp11Processor method testRequestBodySwallowing.
/*
* Tests what happens if a request is completed during a dispatch but the
* request body has not been fully read.
*/
@Test
public void testRequestBodySwallowing() throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
DispatchingServlet servlet = new DispatchingServlet();
Wrapper w = Tomcat.addServlet(ctx, "Test", servlet);
w.setAsyncSupported(true);
ctx.addServletMappingDecoded("/test", "Test");
tomcat.start();
// Hand-craft the client so we have complete control over the timing
SocketAddress addr = new InetSocketAddress("localhost", getPort());
Socket socket = new Socket();
socket.setSoTimeout(300000);
socket.connect(addr, 300000);
OutputStream os = socket.getOutputStream();
Writer writer = new OutputStreamWriter(os, "ISO-8859-1");
InputStream is = socket.getInputStream();
Reader r = new InputStreamReader(is, "ISO-8859-1");
BufferedReader reader = new BufferedReader(r);
// Write the headers
writer.write("POST /test HTTP/1.1\r\n");
writer.write("Host: localhost:8080\r\n");
writer.write("Transfer-Encoding: chunked\r\n");
writer.write("\r\n");
writer.flush();
validateResponse(reader);
// Write the request body
writer.write("2\r\n");
writer.write("AB\r\n");
writer.write("0\r\n");
writer.write("\r\n");
writer.flush();
// Write the 2nd request
writer.write("POST /test HTTP/1.1\r\n");
writer.write("Host: localhost:8080\r\n");
writer.write("Transfer-Encoding: chunked\r\n");
writer.write("\r\n");
writer.flush();
// Read the 2nd response
validateResponse(reader);
// Write the 2nd request body
writer.write("2\r\n");
writer.write("AB\r\n");
writer.write("0\r\n");
writer.write("\r\n");
writer.flush();
// Done
socket.close();
}
use of java.net.SocketAddress in project tomcat by apache.
the class NioReplicationTask method drainChannel.
/**
* The actual code which drains the channel associated with
* the given key. This method assumes the key has been
* modified prior to invocation to turn off selection
* interest in OP_READ. When this method completes it
* re-enables OP_READ and calls wakeup() on the selector
* so the selector will resume watching this channel.
* @param key The key to process
* @param reader The reader
* @throws Exception IO error
*/
protected void drainChannel(final SelectionKey key, ObjectReader reader) throws Exception {
reader.access();
ReadableByteChannel channel = (ReadableByteChannel) key.channel();
int count = -1;
// make buffer empty
buffer.clear();
SocketAddress saddr = null;
if (channel instanceof SocketChannel) {
// loop while data available, channel is non-blocking
while ((count = channel.read(buffer)) > 0) {
// make buffer readable
buffer.flip();
if (buffer.hasArray())
reader.append(buffer.array(), 0, count, false);
else
reader.append(buffer, count, false);
// make buffer empty
buffer.clear();
//do we have at least one package?
if (reader.hasPackage())
break;
}
} else if (channel instanceof DatagramChannel) {
DatagramChannel dchannel = (DatagramChannel) channel;
saddr = dchannel.receive(buffer);
// make buffer readable
buffer.flip();
if (buffer.hasArray())
reader.append(buffer.array(), 0, buffer.limit() - buffer.position(), false);
else
reader.append(buffer, buffer.limit() - buffer.position(), false);
// make buffer empty
buffer.clear();
//did we get a package
count = reader.hasPackage() ? 1 : -1;
}
int pkgcnt = reader.count();
if (count < 0 && pkgcnt == 0) {
//end of stream, and no more packages to process
remoteEof(key);
return;
}
ChannelMessage[] msgs = pkgcnt == 0 ? ChannelData.EMPTY_DATA_ARRAY : reader.execute();
//register to read new data, before we send it off to avoid dead locks
registerForRead(key, reader);
for (int i = 0; i < msgs.length; i++) {
/**
* Use send ack here if you want to ack the request to the remote
* server before completing the request
* This is considered an asynchronous request
*/
if (ChannelData.sendAckAsync(msgs[i].getOptions()))
sendAck(key, (WritableByteChannel) channel, Constants.ACK_COMMAND, saddr);
try {
if (Logs.MESSAGES.isTraceEnabled()) {
try {
Logs.MESSAGES.trace("NioReplicationThread - Received msg:" + new UniqueId(msgs[i].getUniqueId()) + " at " + new java.sql.Timestamp(System.currentTimeMillis()));
} catch (Throwable t) {
}
}
//process the message
getCallback().messageDataReceived(msgs[i]);
/**
* Use send ack here if you want the request to complete on this
* server before sending the ack to the remote server
* This is considered a synchronized request
*/
if (ChannelData.sendAckSync(msgs[i].getOptions()))
sendAck(key, (WritableByteChannel) channel, Constants.ACK_COMMAND, saddr);
} catch (RemoteProcessException e) {
if (log.isDebugEnabled())
log.error(sm.getString("nioReplicationTask.process.clusterMsg.failed"), e);
if (ChannelData.sendAckSync(msgs[i].getOptions()))
sendAck(key, (WritableByteChannel) channel, Constants.FAIL_ACK_COMMAND, saddr);
} catch (Exception e) {
log.error(sm.getString("nioReplicationTask.process.clusterMsg.failed"), e);
if (ChannelData.sendAckSync(msgs[i].getOptions()))
sendAck(key, (WritableByteChannel) channel, Constants.FAIL_ACK_COMMAND, saddr);
}
if (getUseBufferPool()) {
BufferPool.getBufferPool().returnBuffer(msgs[i].getMessage());
msgs[i].setMessage(null);
}
}
if (count < 0) {
remoteEof(key);
return;
}
}
Aggregations