在Java中初始化新套接字会增加RAM使用率

时间:2016-03-23 11:51:58

标签: java sockets jetty

如果关闭,我使用下面的方法保持我的连接活着。我注意到,当它运行了一个星期并且有hundreth套接字时,RAM使用量增加了700 MB。难道我做错了什么?

如果它运行一周而不需要初始化这么多新套接字,则RAM使用量会更小。

import ws.JettyWebSocketClient;

public class connectionKeeper extends Thread {
public void run(){

    lib.print(">>> Connection thread running");


    do{

        lib.writeLog("Opening new websocket connection");

        try{

            GVL.socketCounter++;

            GVL.ws = new JettyWebSocketClient();

            GVL.ws.run();

        }catch(Exception e){
            e.printStackTrace();
            lib.error("Error: connectionKeeper: " + e.toString());
        }

        // if we are here, we got an error or the socket has executed the run() -method to end          
        lib.sleep(2000);

    }while(true);
}

}

-

public class JettyWebSocketClient {

private boolean connected=false;
private WebSocketClient client=new WebSocketClient();

public void run() {

    MyWebSocket socket = new MyWebSocket();

    ClientUpgradeRequest request;

    URI destinationUri = null;
    try {
        destinationUri = new URI("wss://example.com:3000/ws");
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        lib.error("Jetty.runA(): " + e1.toString());
    }

    SslContextFactory sslContextFactory = new SslContextFactory();
    Resource keyStoreResource = Resource.newResource(this.getClass().getResource("/cert.jks"));
    sslContextFactory.setKeyStoreResource(keyStoreResource);
    sslContextFactory.setKeyStorePassword("pass");

    client=new WebSocketClient(sslContextFactory);

    connected=false;

    try {
        client.start();
        request = new ClientUpgradeRequest();
        System.out.println("SOCKET" + GVL.socketCounter+ ":\tConnecting to " + destinationUri.toString());
        client.connect(socket, destinationUri, request);

        do{
            socket.awaitClose(10);
        }while(connected);

    } catch (Throwable t) {
        t.printStackTrace();
        lib.error("Jetty.runB(): " + t.toString());
    }

}


public boolean send(JSONObject message){

    String msg=message.toString();
    System.out.println("SOCKET" + GVL.socketCounter+ ":\tSending msg:\t" + msg);

    for(Session s: client.getOpenSessions()) {
        if (s.isOpen()) {
            try {
                s.getRemote().sendString(msg);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                lib.error(e.toString());
            }
        }
    }

    return false;
}

public String status(){
    return this.client.getState();
}

public boolean isConnected() {
    return connected;
}

public void disconnect(){

    lib.print("Disconnecting...");

    setConnected(false);

    try {

        try{
            client.stop(); 
        } catch (InterruptedException e) {
//   sometimes it gets here, sometimes not.. hmm
        }


    } catch(Exception a){
        lib.error("Jetty.disconnect():\t" + a.toString());
    }

    lib.print("Disconnected...");
}

public void setConnected(boolean newval) {
    connected=newval;
}

@WebSocket
public class MyWebSocket {


    private final CountDownLatch closeLatch = new CountDownLatch(1);

    @OnWebSocketConnect
    public void onConnect(Session session) {

        System.out.println("SOCKET" + GVL.socketCounter+ ":\tCONNECTED");
        setConnected(true);

    }

    @OnWebSocketMessage
    public void onMessage(String message) {
        messaging.handleMsg(message); // this method uses received data to calculate some things
    }

    public void onError(int statusCode, String reason){
        lib.error("SOCKET" + GVL.socketCounter+ ":\tError:\t" + reason + " / Code: " + statusCode);
    }

    @OnWebSocketClose
    public void onClose(int statusCode, String reason)  {
        lib.error("SOCKET" + GVL.socketCounter+ ":\tClosed:\t" + reason + " / Code: " + statusCode);

        setConnected(false);

     }

    public void awaitClose(int n) {
        try {
            this.closeLatch.await(n, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
            lib.error("SOCKET" + GVL.socketCounter+ ": Jetty.awaitClose():" + e.toString());

            disconnect(); // useless?
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

不要继续重新创建WebSocketClient对象,只需创建其中一个并在需要时重新连接。

WebSocketClient视为浏览器。

  • 启动该浏览器时每个client.start()
  • 每个client.connect()在您打开新网页的标签时。

昂贵的操作,启动浏览器,你一遍又一遍地做。 廉价的操作,连接到一个网站,打开新标签,关闭其他人,你没有做。 相反,你要“dang,我需要重新连接,让我停止浏览器,然后重新启动它以重新连接”