Here is my client side source code:
public class Client
{
Server server;
Logger logger;
ChannelHandlerContext responseCtx;
public Client(String host, int port, int mode, String fileName)
{
server=null;
EventLoopGroup group = new NioEventLoopGroup();
try
{
Bootstrap b = new Bootstrap();
b.group(group);
b.channel(NioSocketChannel.class);
b.remoteAddress(new InetSocketAddress(host, port));
b.handler(new MyChannelInitializer(server, mode,fileName));
ChannelFuture f = b.connect().sync();
f.channel().closeFuture().sync();
System.out.println("client started");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
try {
group.shutdownGracefully().sync();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar endTime=Calendar.getInstance();
System.out.println("client stopped "+endTime.getTimeInMillis());
}
}
public static void main(String[] args) throws Exception
{
#SuppressWarnings("unused")
Client c=new Client("localhost",1234,MyFtpServer.SENDFILE,"D:\\SITO3\\Documents\\Xmas-20141224-310.jpg");
}
}
Here is my File Transfer Complete Listener source code:
public class FileTransferCompleteListener implements ChannelFutureListener
{
Server server;
public FileTransferCompleteListener(Server server)
{
this.server=server;
}
#Override
public void operationComplete(ChannelFuture cf) throws Exception
{
Calendar endTime=Calendar.getInstance();
System.out.println("File transfer completed! "+endTime.getTimeInMillis());
if(server!=null)
server.stop();
else
cf.channel().close();
}
}
Here is the execution result:
File transfer completed! 1451446521041
client started
client stopped 1451446523244
I want to know why it takes about 2 second to close connection.
Is it any way to reduce it?
thank you very much
Take a look at shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit), you can specify the quietPeriod, by default it is a couple of seconds.
I’m not sure what the implications are if you shorten this.
Related
I try to create a client which will retry connect when previous connection timeout. This program tries to connect to localhost:8007 which port 8007 is without any service, so the program will retry after connection time out. But this code will free after running for a while. The program freezes when there are about 3600 threads. I expect it will continue to retry rather than it will freeze.
The standard output's last output is "retry connect begin".
Does anyone know the reason why it will freeze?
JProfiler: program's Thread statistic, shows 2 threads are blocked on java.lang.ThreadGroup:
JProfiler showing program's Thread statistic
public final class EchoClient2 {
static final boolean SSL = System.getProperty("ssl") != null;
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));
static final int SIZE = Integer.parseInt(System.getProperty("size", "256"));
public static void main(String[] args) throws Exception {
// Configure SSL.git
EchoClient2 echoClient2 = new EchoClient2();
echoClient2.connect();
}
public void connect() throws InterruptedException {
final SslContext sslCtx;
// Configure the client.
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10)
.handler(new ChannelInitializer<SocketChannel>() {
#Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
//p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new EchoClientHandler());
}
});
// Start the client.
ChannelFuture f = b.connect(HOST, PORT);
f.addListener(new ConnectionListener());
System.out.println("add listener");
f.sync();
System.out.println("connect sync finish");
// Wait until the connection is closed.
f.channel().closeFuture().sync();
System.out.println("channel close");
} finally {
// Shut down the event loop to terminate all threads.
//group.shutdownGracefully();
}
}
}
public class ConnectionListener implements ChannelFutureListener {
#Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
System.out.println("enter listener");
EventLoop eventLoop = channelFuture.channel().eventLoop();
eventLoop.schedule(new Runnable() {
#Override
public void run() {
try {
System.out.println("retry connect begin");
new EchoClient2().connect();
System.out.println("retry connect exit");
} catch (InterruptedException e) {
System.out.println(e);
e.printStackTrace();
}
}
}, 10, TimeUnit.MILLISECONDS);
System.out.println("exit listener");
}
}
Since I am stuck for this for a week now and still haven't firgured it out I try to express what I want as cleary as possible.
I have a Server which can handle Multiple Clients and communicates with them.
Whenever a client connects, the server passes the Client's request to my class RequestHandler, in which the clients commands are being processed.
If one of the clients says "SHUTDOWN", the server is supposed to cut them loose and shut down.
It doesn't work.
If only one client connects to the server, the server seems to be stuck in the accept() call and I do not know how to fix this.
THERE is already one response, but please do not take note of it, it was on a different topic which is outdated
I have two approaches and both don't seem to work.
1)If the client writes "SHUTDOWN", the shutdownFlag is set to true (in hope to exit the while loop)
2)If the client writes "SHUTDOWN", the static method shutdown() is called on the Server, which should shut him down
Below you see the implementation of my Server class, the other two classes involved are Client(all he does is connect to the Socket) and RequestHandler (this class processes the Input and writes it) .
I am 98% sure the problem lies within the Server class.
Below this is an even shorter version of the Server with just the methods without any Console outputs which might help understanding it in case you want to copy the code
public class Server {
public static final int PORTNUMBER = 8540;
public static final int MAX_CLIENTS = 3;
public static boolean shutdownFlag = false;
public static ExecutorService executor = null;
public static ServerSocket serverSocket = null;
public static void main(String[] args) {
ExecutorService executor = null;
try (ServerSocket serverSocket = new ServerSocket(PORTNUMBER);) {
executor = Executors.newFixedThreadPool(MAX_CLIENTS);
System.out.println("Waiting for clients");
while (!shutdownFlag) {
System.out.println("shutdown flag ist : " + shutdownFlag);
Socket clientSocket = serverSocket.accept();
Runnable worker = new RequestHandler(clientSocket);
executor.execute(worker);
System.out.println("Hallo");
}
if (shutdownFlag) {
System.out.println("Flag is on");
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//Stop accepting requests.
serverSocket.close();
} catch (IOException e) {
System.out.println("Error in server shutdown");
e.printStackTrace();
}
serverSocket.close();
}
System.out.println("shutting down");
} catch (IOException e) {
System.out
.println("Exception caught when trying to listen on port "
+ PORTNUMBER + " or listening for a connection");
System.out.println(e.getMessage());
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static void shutdown(){
if (shutdownFlag) {
System.out.println("Flag is on");
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
//Stop accepting requests.
serverSocket.close();
} catch (IOException e) {
System.out.println("Error in server shutdown");
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Server {
public static final int PORTNUMBER = 8540;
public static final int MAX_CLIENTS = 3;
public static boolean shutdownFlag = false;
public static ExecutorService executor = null;
public static ServerSocket serverSocket = null;
public static void main(String[] args) {
ExecutorService executor = null;
try (ServerSocket serverSocket = new ServerSocket(PORTNUMBER);) {
executor = Executors.newFixedThreadPool(MAX_CLIENTS);
while (!shutdownFlag) {
Socket clientSocket = serverSocket.accept();
Runnable worker = new RequestHandler(clientSocket);
executor.execute(worker);
}
if (shutdownFlag) {
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
serverSocket.close();
}
} catch (IOException e) {
} finally {
if (executor != null) {
executor.shutdown();
}
}
}
public static void shutdown() {
if (shutdownFlag) {
try {
executor.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If you move the code in main into an instance method on Server (we'll say run here) you can just do new Server().run() inside main. That way you have an instance (this) to work with inside your run method.
Something like this:
class Server {
private boolean shutdownFlag = false; // This can't be static anymore.
public static final Server SERVER = new Server();
public static void main(String[] args) {
SERVER.run();
}
private void run() {
// Here goes everything that used to be inside main...
// Now you have the Server.SERVER instance to use outside the class
// to shut things down or whatever ...
}
}
This pattern isn't actually that great but better would be too long for here. Hopefully this gets you off to a good start.
Scenario:
a) Persistent connections
b) Manage each server-client communication individually
c) Protect System from propagating exceptions/errors
I tried to created two instances of server socket listeners using the following code :
SimpleSocketServers.java
public class SimpleSocketServers {
public static void main(String[] args) throws Exception {
int port1 = 9876;
SimpleSocketServer server1 = new SimpleSocketServer(port1);
server1.startAndRunServer();
System.out.println("Servers : server1 Listening on port: " + port1);
int port2 = 9875;
SimpleSocketServer server2 = new SimpleSocketServer(port2);
server2.startAndRunServer();
System.out.println("Servers : server2 Listening on port: " + port2);
}
}
and
SimpleSocketServer.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleSocketServer {
private ServerSocket serverSocket;
private int port;
public SimpleSocketServer(int port) {
this.port = port;
}
public void startAndRunServer() {
try {
System.out.println("Starting Server at port " + port + " ...");
serverSocket = new ServerSocket(port);
System.out.println("Listening for client connection ...");
Socket socket = serverSocket.accept();
RequestHandler requestHandler = new RequestHandler(socket);
requestHandler.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class RequestHandler extends Thread {
private Socket socket;
RequestHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
System.out.println("Client Request Response being processed...");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
}
But, it creates only one instance as control is not returning from the constructor of first instance. Is there any possibility to get back control and run both instances of server socket listeners simultaneously? (ps: Pardon me, if it is wrong or trivial!)
Use 2 Different Threads, Listening To 2 Different Ports.
Thread ServerThread1 = new Thread(new Runnable() {
#Override
public void run() {
ServerSocket ServerSocketObject = null;
while(true)
{
try {
ServerSocketObject = new ServerSocket(Your_Port_Number1);
Socket SocketObject = ServerSocketObject.accept();
// Your Code Here
SocketObject.close();
} catch (IOException e) {
try {
ServerSocketObject.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
});
Thread ServerThread2 = new Thread(new Runnable() {
#Override
public void run() {
ServerSocket ServerSocketObject = null;
while(true)
{
try {
ServerSocketObject = new ServerSocket(Your_Port_Number2);
Socket SocketObject = ServerSocketObject.accept();
// Your Code Here
SocketObject.close();
} catch (IOException e) {
try {
ServerSocketObject.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
}
});
ServerThread1.start();
ServerThread2.start();
You need to have SimpleSocketServer implement Runnable; start a thread with itself as the Runnable in the constructor; and run an accept() loop in the run() method. At present you're blocking in the constructor waiting for a connection, and your servers will also only handle a single connection.
The more interesting question is why you want to provide the same service on two ports.
For a chat server project I use netty as server, with the following code in my handler :
public class PacketHandler extends ChannelInboundHandlerAdapter{
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf in = (ByteBuf) msg;
try {
AbstractClientPacket packet = ClientPacketHandler.handle(in);
if(packet != null && packet.read()){
packet.run();
ctx.write(msg+"\r\n");
}
} finally {
ReferenceCountUtil.release(msg);
}
}
#Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
So, my packet is correctly handled and it works fine, but then, i do ctx.write(msg+"\r\n"); to send back the message to my client, acting like an echo server.
Here is the Client's code :
public class ChatClient {
static Socket socket;
static DataOutputStream out;
static BufferedReader in;
public static void main(String[] args){
try {
initSocket();
String test = "Salut 1";
TestPacket packet = new TestPacket(0x18,test.getBytes());
sendPacket(packet);
while(true){
try {
String message = in.readLine();
System.out.println(message);
} catch (IOException e) {
e.printStackTrace();
}
}
//TEST
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static void initSocket(){
try {
socket = new Socket("localhost",58008);
out = new DataOutputStream(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader((socket.getInputStream())));
} catch (IOException e) {
e.printStackTrace();
}
}
private static void sendPacket(TestPacket p) throws IOException{
out.write(p.getRawData());
out.flush();
}
}
The packet is correctly sent, but i get nothing as reply, and when i stop my server, the client is spamming null because of my while(true), but i don't get my message back, nothing is displayed and i really don't know why.
I can't use netty for the client because this one is just for test purpose, the final client will be written in C# (Unity Engine), so i can't use netty in this one, I have to do it with native socket handling.
EDIT:
According to wireshark, The packet from client is sent but the server answer is not, i don't see the packet From server containing "Salut 1".
You did:
ctx.write(msg+"\r\n");
msg is not a String but a ByteBuf. If you want to append \r\n to the received message, you should do the following:
in.writeByte('\r');
in.writeByte('\n');
ctx.write(in);
Also, because you reused the received message (in) as a response, you should not release it:
// Do NOT call this.
ReferenceCountUtil.release(in);
If you really intended to call ctx.write(msg + "\r\n"), please make sure that your pipeline has StringEncoder.
I'm trying to implement OSGI bundle with network server which uses network sockets.
This is the complete source code: http://www.2shared.com/file/RMXby331/CB_27.html
This is the Activator:
package org.DX_57.osgi.CB_27.impl;
import java.util.Properties;
import org.DX_57.osgi.CB_27.api.CBridge;
import org.DX_57.osgi.CB_27.impl.EchoServer;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
public class CBridgeApp implements BundleActivator {
public void start(BundleContext bc) throws Exception {
ServiceRegistration registerService = bc.registerService(CBridge.class.getName(), new CBridgeImpl(), new Properties());
EchoServer();
}
public void stop(BundleContext bc) throws Exception {
boolean ungetService = bc.ungetService(bc.getServiceReference(CBridge.class.getName()));
}
private void EchoServer() {
EchoServer method = new EchoServer();
}
}
This is the source code if the Java Network server:
package org.DX_57.osgi.CB_27.impl;
import java.net.*;
import java.io.*;
public class EchoServer
{
ServerSocket m_ServerSocket;
public EchoServer()
{
try
{
// Create the server socket.
m_ServerSocket = new ServerSocket(12111);
}
catch(IOException ioe)
{
System.out.println("Could not create server socket at 12111. Quitting.");
System.exit(-1);
}
System.out.println("Listening for clients on 12111...");
// Successfully created Server Socket. Now wait for connections.
int id = 0;
while(true)
{
try
{
// Accept incoming connections.
Socket clientSocket = m_ServerSocket.accept();
// accept() will block until a client connects to the server.
// If execution reaches this point, then it means that a client
// socket has been accepted.
// For each client, we will start a service thread to
// service the client requests. This is to demonstrate a
// multithreaded server, although not required for such a
// trivial application. Starting a thread also lets our
// EchoServer accept multiple connections simultaneously.
// Start a service thread
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
cliThread.start();
}
catch(IOException ioe)
{
System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
}
}
}
public static void main (String[] args)
{
new EchoServer();
}
class ClientServiceThread extends Thread
{
Socket m_clientSocket;
int m_clientID = -1;
boolean m_bRunThread = true;
ClientServiceThread(Socket s, int clientID)
{
m_clientSocket = s;
m_clientID = clientID;
}
public void run()
{
// Obtain the input stream and the output stream for the socket
// A good practice is to encapsulate them with a BufferedReader
// and a PrintWriter as shown below.
BufferedReader in = null;
PrintWriter out = null;
// Print out details of this connection
System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " +
m_clientSocket.getInetAddress().getHostName());
try
{
in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));
// At this point, we can read for input and reply with appropriate output.
// Run in a loop until m_bRunThread is set to false
while(m_bRunThread)
{
// read incoming stream
String clientCommand = in.readLine();
System.out.println("Client Says :" + clientCommand);
if(clientCommand.equalsIgnoreCase("quit"))
{
// Special command. Quit this thread
m_bRunThread = false;
System.out.print("Stopping client thread for client : " + m_clientID);
}
else
{
// Echo it back to the client.
out.println(clientCommand);
out.flush();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
// Clean up
try
{
in.close();
out.close();
m_clientSocket.close();
System.out.println("...Stopped");
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
}
When I try to deploy the bundle on Glassfish server the application server hangs but I can connect to the java network server using the java client. It seems that there is a infinite loop. I need help to fix the code.
Best wishes
Your bundle activator start method never returns, because you're calling constructor of your service with infinite loop. A good practice is to return as fast as possible from bundle activators.
Here is an idea how to rewrite your code:
public class EchoServer {
private volatile boolean started;
public void start() {
new Thread(new Runnable() {
#Override
public void run() {
started = true;
try {
m_ServerSocket = new ServerSocket(12111);
} catch(IOException ioe) {
System.out.println("Could not create server socket at 12111. Quitting.");
System.exit(-1);
}
System.out.println("Listening for clients on 12111...");
// Successfully created Server Socket. Now wait for connections.
int id = 0;
while (started) {
try {
Socket clientSocket = m_ServerSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
cliThread.start();
} catch(IOException ioe) {
System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
}
}
}
}).start();
}
public void stop() {
started = false;
}
}
Activator
public class CBridgeApp implements BundleActivator {
private EchoServer method;
public void start(BundleContext bc) throws Exception {
...
method = new EchoServer();
method.start();
}
public void stop(BundleContext bc) throws Exception {
...
method.stop();
}
}