i am coding a http server with netty-all-4.1.0.Final.jar,while the server listening,sometimes while happen "connection reset by peer",the detail like below:
Connection reset by peer
java.io.IOException: Connection reset by peer
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:192)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1098)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:350)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:112)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:544)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:485)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:399)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:371)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:742)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:145)
at java.lang.Thread.run(Thread.java:748)
this is my main server code:
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
//将同一个http请求的内容组装到一起,调用一次handler
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new HttpServerHandler());
}
});
int port = ConfUtils.port;
ChannelFuture f = b.bind(port).sync();
logger.info("start lisner-------port is {}",port);
f.channel().closeFuture().sync();
} catch(Exception e){
logger.error(e.getMessage(),e);
}
finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
this is my handler class:
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if(msg instanceof FullHttpRequest){
try{
logger.info("accept http msg!");
FullHttpRequest fullHttpRequest = (FullHttpRequest)msg;
ProcessMsg.dealMsg(fullHttpRequest);
logger.info("full header is {}",fullHttpRequest);
String responseHtml = "response from server!";
byte[] responseBytes = responseHtml.getBytes("UTF-8");
int contentLength = responseBytes.length;
FullHttpResponse response = new
DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK,Unpooled.wrappedBuffer(responseBytes));
response.headers().set("Content-Type", "text/html; charset=utf-8");
response.headers().set("Content-Length", Integer.toString(contentLength));
Thread.sleep(1000 * 5);
ctx.writeAndFlush(response);
ctx.flush();
logger.info("response from server!");
}catch(Exception e){
logger.error(e.getMessage(),e);
}
}
else{
logger.info("this is not http request");
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
LoggerFactory.getLogger("excplog").error(cause.getMessage(),cause);
ctx.close();
}
}
it's not always happend,sometimes happen and most times not,and we can't find any question about request
Related
Unable to capture a screenshot using extent report 4(Selenium-Java)
Error msg is :-
FAILED CONFIGURATION: #AfterMethod tearDown([TestResult name=expediaTitleCheck status=FAILURE method=Expedia_TC.expediaTitleCheck()[pri:0, instance:com.extent.testcases.Expedia_TC#72b6cbcc] output={null}])
Code is as follows:-
public class Expedia_TC {
WebDriver driver;
Expedia exp;
ExtentHtmlReporter htmlReport;
ExtentReports extent;
ExtentTest test;
#BeforeTest
public void startBrowser() {
htmlReport = new ExtentHtmlReporter(System.getProperty("user.dir")+"/Reports/ExpediaReport.html");
htmlReport.config().setEncoding("utf-8");
htmlReport.config().setDocumentTitle("Expedia Automation Report");
htmlReport.config().setReportName("Functional Report");
htmlReport.config().setTimeStampFormat("EEEE,DD-MM-YYYY,hh:mm:ss");
htmlReport.config().setTheme(Theme.DARK);
extent = new ExtentReports();
extent.attachReporter(htmlReport);
extent.setSystemInfo("OS","Windows10");
extent.setSystemInfo("Environment","Production");
extent.setSystemInfo("Tester","Jayashree");
WebDriverManager.firefoxdriver().setup();
System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE, "true");
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"/dev/null");
driver = new FirefoxDriver();
exp = new Expedia(driver);
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
}
#Test
public void expediaTitleCheck() {
test = extent.createTest("Title Check Test...");
exp.checkPageTitle();
test.fail("This Test is Failed!");
}
#AfterMethod
public void tearDown(ITestResult result)throws IOException {
if(result.getStatus() == ITestResult.FAILURE) {
String methodName ="<b>"+result.getMethod().getMethodName()+" : "+"FAILED"+"</b>";
String errorMsg = "<b>"+"REASON: "+" "+result.getThrowable().getMessage()+"</b>";
String failureScreenshot = Expedia_TC.captureScreen(driver, methodName);
test.log(Status.FAIL,MarkupHelper.createLabel(methodName,ExtentColor.RED));
test.log(Status.FAIL,errorMsg);
try {
test.addScreenCaptureFromPath(failureScreenshot);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
#AfterTest
public void endReport() {
extent.flush();
driver.quit();
}
So I'm tying to develop a very simple TeamCity Plugin. The Plugin is just suppose to take user input and display it. My code seems to work on my local Tomcat server but when i try to integrate it into TeamCity via the Basecontroller class from jetbrains there seems to be no output. This is my code
public class AppServer extends BaseController{
private PluginDescriptor myDescriptor;
public AppServer (WebControllerManager manager, PluginDescriptor descriptor) {
manager.registerController("/demoPlugin.html",this);
myDescriptor=descriptor;
}
public void doGet(HttpServletRequest request, HttpServletResponse responseone)throws IOException, ServletException {
try {
responseone.setContentType("text/html; charset=UTF-8");
PrintWriter out = responseone.getWriter();
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
out.println("<title>Echo Servlet</title></head>");
out.println("<body><h2>You have enter</h2>");
String requirement = request.getParameter("requirement");
if (requirement == null || (requirement = htmlFilter(requirement.trim())).length() == 0) {
out.println("<p>Agent Requirement: Not specified</p>");
}
else {
out.println("<p>Agent Requirement: " + requirement + "</p>");
}
out.println("<a href='form_input.html'>BACK</a>");
out.println("</body></html>");
}
finally{
out.close();
}
}
finally{
return;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse responseone)
throws IOException, ServletException {
doGet(request, responseone);
}
private static String htmlFilter(String message) {
if (message == null) return null;
int len = message.length();
StringBuffer result = new StringBuffer(len + 20);
char aChar;
for (int i = 0; i < len; ++i) {
aChar = message.charAt(i);
switch (aChar) {
case '<': result.append("<"); break;
case '>': result.append(">"); break;
case '&': result.append("&"); break;
case '"': result.append("""); break;
default: result.append(aChar);
}
}
return (result.toString());
}
protected ModelAndView doHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws Exception {
return new ModelAndView(myDescriptor.getPluginResourcesPath("Hello.jsp"));
}
}
I honestly don't know what I'm doing and I cannot seem to find any good tutorials regarding Basecontroller class from jetbrains. Please help.
I want to read a list of url to the same site which support http 1.1 keep-live.
I try to use netty to do this and it works.
but when i get the response,i can not identify it is for which url.
how can i get the request url from method messageReceived below:
public static void main(String[] args) throws InterruptedException, URISyntaxException {
String host = "localhost";
int port = 8080;
String[] paths = new String[]{"1.html", "2.html", "3.html"};
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpClientCodec());
p.addLast(new HttpContentDecompressor());
p.addLast(new SimpleChannelInboundHandler<HttpObject>() {
#Override
protected void messageReceived(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
System.out.println("response from url ?:" + content.content().toString());
}
}
});
}
});
Channel ch = b.connect(host, port).sync().channel();
for (String path : paths) {
HttpRequest request = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, path);
request.headers().set(HttpHeaderNames.HOST, host);
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
ch.writeAndFlush(request);
}
Try this:
p.addLast(new SimpleChannelInboundHandler<Object>() {
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
System.out.println("I'm HttpRequest");
FullHttpRequest req = (FullHttpRequest) msg;
if (HttpHeaders.is100ContinueExpected(req)) {
ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
}
System.out.println("response from url ?:" + req.getUri());
ByteBuf content = req.content();
}
}
});
Don't know what version of netty are you using. If 5.0+, rename channelRead to messageReceived.
I try to use Kryonet to create an online game.
When I give the ip adress (hardcoded in the code), connection and sendind/receiving works.
But if I try to discover the server, It's never responding me: the method always return null.
Server:
public static int UDP_PORT = 54723, TCP_PORT = 54722;
public static void main(String args[]) {
/* ***** server starting ***** */
Server server = new Server();
server.start();
try {
server.bind(TCP_PORT, UDP_PORT);
} catch (IOException e) {
System.out.println("server not deployed");
e.printStackTrace();
System.exit(1);
}
System.out.println("server started");
server.addListener(new ServerListener());
}
Client:
public static void main(String[] args) {
Client client = new Client();
client.start();
InetAddress addr = client.discoverHost(UDP_PORT, 10000);
System.out.println(addr);
if(addr == null) {
System.exit(0);
}
try {
client.connect(5000, addr, TCP_PORT, UDP_PORT);
} catch (IOException e) {
e.printStackTrace();
}
for(int i = 0; i < 100; i++) {
client.sendTCP(new String("bouh" + i));
}
client.close();
}
What's wrong in this code?
Note that my tests are launched on localhost. Is it a problem here ?
Thank's for all reponse.
Jonathan
If you are having the same problem I had related to discover hosts (http://code.google.com/p/kryonet/issues/detail?id=29) then checking out the project from SVN (instead of using the 2.20 zip file) fixed the issue for me.
I'm trying to connect to SSH Unix server on button click (code written in actionPerformed() method). I'm using JSch for connecting to SSH server. The code is written in SwingWorker class as it is a network operation.
private void testConnectionButtonActionPerformed(java.awt.event.ActionEvent evt) {
SwingWorker<Boolean, Void> sw = new SwingWorker<Boolean, Void>(){
#Override
protected Boolean doInBackground() throws Exception {
JSch jsch = new JSch();
String host = "ServerHost";
String username = "username";
String password = "password";
Session session = jsch.getSession(username, host);
session.setPassword(password);
session.setTimeout(20000);
System.out.println("Connecting to server...");
session.connect();
return true;
}
#Override
public void done(){
try {
System.out.println(get().toString());
} catch (Exception ex) {
System.out.err(ex);
}
}
};
sw.execute();
}
But after running the with correct host, username and password details, I get the below error all the time:
com.jcraft.jsch.JSchException: timeout: socket is not established
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
at java.util.concurrent.FutureTask.get(FutureTask.java:83)
at javax.swing.SwingWorker.get(SwingWorker.java:583)
But whenever I run the same code in standalone program, I mean instead for writing actionPerformed() method, If I write it in normal method and calling from main() method. It will work. when I integrate the same code with Button Click's actionPerformed() method, it will give me above exception.
Can anyone suggest what I'm doing wrong here or any modification should be made to the code.
I tried to connect to SSH Server using "SSHJ" implementation, but I get the below error:
java.net.SocketException: Connection reset
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
at java.util.concurrent.FutureTask.get(FutureTask.java:83)
at javax.swing.SwingWorker.get(SwingWorker.java:583)
Can someone help me - how to move forward?
I took your code, wrapped it in some GUI code (and converted it to non-generics to be able to compile it with the same settings as the rest of the JSch examples). It works for me. Try this, and report what exception you get (it has a bit more exception logging).
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import com.jcraft.jsch.*;
class SwingWorkerExample {
JTextField hostField;
JTextField userNameField;
JTextField passwordField;
JPanel panel;
public SwingWorkerExample() {
JPanel p = panel = new JPanel(new GridLayout(0,2));
hostField = new JTextField(20);
userNameField = new JTextField(20);
passwordField = new JPasswordField(20);
JButton testButton = new JButton("connect!");
testButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
testConnectionButtonActionPerformed(ev);
}
});
p.add(new JLabel("host:"));
p.add(hostField);
p.add(new JLabel("user:"));
p.add(userNameField);
p.add(new JLabel("password:"));
p.add(passwordField);
p.add(testButton);
}
public JPanel getPanel() {
return panel;
}
private void testConnectionButtonActionPerformed(ActionEvent evt) {
SwingWorker sw = new SwingWorker(){
protected Object doInBackground() throws Exception {
try {
JSch jsch = new JSch();
String host = hostField.getText();
String username = userNameField.getText();
String password = passwordField.getText();
Session session = jsch.getSession(username, host);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.setTimeout(20000);
System.out.println("Connecting to server...");
session.connect();
return session;
}
catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
}
public void done(){
try {
System.out.println(get());
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
sw.execute();
}
public static void main(String[] egal) {
EventQueue.invokeLater(new Runnable(){public void run() {
SwingWorkerExample ex = new SwingWorkerExample();
JFrame f = new JFrame("bla");
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setContentPane(ex.getPanel());
f.pack();
f.setVisible(true);
}});
}
}