2013-09-16 3 views
0

Я получаю исключение транспорта и исключение EOF на стороне клиента при использовании CometD. Я попытался найти решение через документацию CometD, а также googled, но не смог найти какое-либо решение.gettting transport и исключение EOF с CometD со стороны клиента

Ниже трассировку стека исключений я получаю

CommetD Connected!!!!!!! 
cometDURL http://192.168.210.106:8080/cometd2/cometd 
subscriberChannel /service/java 
In finally........... 
2013-09-12 10:20:26,200 [HttpClient-201] INFO org.cometd.client.BayeuxClient.180910783  - Messages failed [{id=31, connectionType=long-polling, channel=/meta/connect, clientId=2qpitkhfcjh1g511al4xal9vltg}] 
org.cometd.common.TransportException at org.cometd.client.transport.LongPollingTransport$TransportExchange.onResponseComplete(LongPollingTransport.java:334) at org.eclipse.jetty.client.HttpExchange$Listener.onResponseComplete(HttpExchange.java:999) 
      at org.eclipse.jetty.client.HttpExchange.setStatus(HttpExchange.java:288) 
      at org.eclipse.jetty.client.HttpConnection$Handler.messageComplete(HttpConnection.java:628) 
      at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:786) 
      at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:220) 
      at org.eclipse.jetty.client.HttpConnection.handle(HttpConnection.java:275) 
      at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:545) 
      at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:43) 
      at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:529) 
      at java.lang.Thread.run(Thread.java:662) 

java.io.EOFException: closed: [email protected]=POST//192.168.145.210:8080/cometd2/cometd#WAITING(64ms)sent=64ms 
      at org.eclipse.jetty.client.HttpConnection.close(HttpConnection.java:663) 
      at org.eclipse.jetty.client.HttpDestination.close(HttpDestination.java:639) 
      at org.eclipse.jetty.client.HttpClient.doStop(HttpClient.java:491) 
      at org.eclipse.jetty.util.component.AbstractLifeCycle.stop(AbstractLifeCycle.java:83) 
      at com.commetd.CommetD.publish(CommetD.java:58) 
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
      at java.lang.reflect.Method.invoke(Method.java:597) 
      at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:301) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) 
      at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
      at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) 
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
      at java.lang.reflect.Method.invoke(Method.java:597) 
      at sun.reflect.GeneratedMethodAccessor72.invoke(Unknown Source) 
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
      at java.lang.reflect.Method.invoke(Method.java:597) 
      at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:301) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) 
      at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
      at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) 
      at $Proxy25.callProxy(Unknown Source) 
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
      at java.lang.reflect.Method.invoke(Method.java:597) 
      at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:301) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) 
      at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
      at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) 
      at $Proxy171.publishEventToBulletinManager(Unknown Source) 
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) 
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) 
      at java.lang.Thread.run(Thread.java:662) 

Я использовал следующий код для подключения к CometD серверу

public static boolean publish(String cometDURL,String subscriberChannel,Map<String,Object> msgToPublish) throws Exception{ 
    boolean isSuccess = true; 

    HttpClient httpClient = new HttpClient(); 
    BayeuxClient client = null; 
    ClientTransport transport=null; 
    // Here setup Jetty's HttpClient, for example: 
    httpClient.setMaxConnectionsPerAddress(10); 
    try { 
     httpClient.start(); 

     Map<String, Object> options = new HashMap<String, Object>(); 

     transport = LongPollingTransport.create(options, httpClient); 

     client = new BayeuxClient(cometDURL, transport); 

     client.handshake(); 


     boolean handshaken = client.waitFor(1000, BayeuxClient.State.CONNECTED); 
     if(handshaken){ 
      System.out.println("CommetD Connected!!!!!!!"); 
      /*Map<String,Object> data = new HashMap<String,Object>(); 
      data.put("name", "Java msg......... Dynamic msg.....");*/ 
      // Fill in the data 
      client.getChannel(subscriberChannel).publish(msgToPublish); 

     }else{ 
      isSuccess=false; 
      System.out.println("CommetD not connected:-("); 
     } 
    } catch (Exception e) { 
     isSuccess=false; 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    }finally{ 
     client.disconnect(); 
     client.waitFor(1000, BayeuxClient.State.DISCONNECTED); 
     transport.terminate(); 
     httpClient.stop(); 
    } 

    return isSuccess; 

} 

стороне сервера код

@Listener("/service/java") 
public void processMsgFromJava(ServerSession remote, ServerMessage.Mutable message) 
{ 
    System.out.println("Received msg from java.................."); 
    Map<String, Object> input = message.getDataAsMap(); 
    String eventId = (String)input.get("eventID"); 
    String updatedDate = (String)input.get("updatedDate"); 
    // String channelName =(String)input.get("ChannelToPublish"); 
    System.out.println("msg received : "+eventId+":"+updatedDate); 
    // Map<String, Object> output = new HashMap<String, Object>(); 
    //output.put("greeting", name); 
    // remote.deliver(serverSession, "/java/test", output, null); 

    String channelName = "/java/test"; 
    // Initialize the channel, making it persistent and lazy 
    bayeux.createIfAbsent(channelName, new ConfigurableServerChannel.Initializer() 
    { 
     public void configureChannel(ConfigurableServerChannel channel) 
     { 
      channel.setPersistent(true); 
      channel.setLazy(true); 
     } 
    }); 

    // System.out.println("HHHHHHHHHHHHREEEEEEEEEEEEEEEEEEEEEEEEERRRRRRRRRRRRRRRRRRRRRRRRRRRRREEEEEEEEEE"); 
    // Convert the Update business object to a CometD-friendly format 
    /* Map<String, Object> data = new HashMap<String, Object>(); 
    data.put("javamsg", name);*/ 


    // Publish to all subscribers 
    ServerChannel channel = bayeux.getChannel(channelName); 
    channel.publish(serverSession, input, null); 
} 

javascript на стороне клиента:

(function($) 
{ 
var cometd = $.cometd; 

$(document).ready(function() 
{ 
    function _connectionEstablished() 
    { 
     $('#body').append('<div>CometD Connection Established</div>'); 
    } 

    function _connectionBroken() 
    { 
     $('#body').append('<div>CometD Connection Broken</div>'); 
    } 

    function _connectionClosed() 
    { 
     $('#body').append('<div>CometD Connection Closed</div>'); 
    } 

    // Function that manages the connection status with the Bayeux server 
    var _connected = false; 
    function _metaConnect(message) 
    { 
     if (cometd.isDisconnected()) 
     { 
      _connected = false; 
      _connectionClosed(); 
      return; 
     } 

     var wasConnected = _connected; 
     _connected = message.successful === true; 
     if (!wasConnected && _connected) 
     { 
      _connectionEstablished(); 
     } 
     else if (wasConnected && !_connected) 
     { 
      _connectionBroken(); 
     } 
    } 

    // Function invoked when first contacting the server and 
    // when the server has lost the state of this client 
    function _metaHandshake(handshake) 
    { 
     if (handshake.successful === true) 
     { 
      cometd.batch(function() 
      { 
       cometd.subscribe('/java/test', function(message) 
       { 
        $('#body').append('<div>Server Says: ' + message.data.eventID + ':'+ message.data.updatedDate + '</div>'); 
       }); 
       // Publish on a service channel since the message is for the server only 
       // cometd.publish('/service/hello', { name: 'World' }); 
      }); 
     } 
    } 

    // Disconnect when the page unloads 
    $(window).unload(function() 
    { 
     cometd.disconnect(true); 
    }); 

    var cometURL = location.protocol + "//" + location.host + config.contextPath + "/cometd"; 
    cometd.configure({ 
     url: cometURL, 
     logLevel: 'debug' 
    }); 

    cometd.addListener('/meta/handshake', _metaHandshake); 
    cometd.addListener('/meta/connect', _metaConnect); 

    cometd.handshake(); 
}); 
})(jQuery); 

Может ли кто-нибудь помочь мне в решении этой проблемы. Я не уверен, где я ошибаюсь.

ответ

0

Прежде всего, вы используете что-то под названием com.commetd.CommetD, что не является стандартным кодом CometD. Неясно, является ли код, который вы показываете, кодом для этого класса.

Предполагая, что это простая оболочка к исходному коду CometD, трассировка стека объясняет все это: вы останавливаете HttpClient с помощью метода publish(), который не имеет смысла.

Пожалуйста, внимательно прочитайте CometD concepts и как использовать CometD client library.

+0

Hi sbordet, Спасибо за ответ. Метод публикации, который я поделил здесь, - это метод, который я написал для подключения к CometD и для отправки данных в CometD. Здесь, если я не останавливаю httpclient, транспорт и клиент в блоке finally. Он занимает много памяти, увеличивая количество подключений tcp/ip. С этим мое затмение разбилось из-за недостатка памяти. Я думал, что приведенная ниже строка уже опубликована в CometD. Я могу остановить этот httpclient, client.getChannel (subscriberChannel) .publish (msgToPublish); Если не здесь, где я должен остановиться без проблем. Пожалуйста, направляйте меня. – raajaag

+0

Я удалил код в блоке finally в com.commetd.CommetD методом публикации (мой собственный класс), с этим я не получаю исключение EOF, но Транспортное исключение все еще существует. Я не уверен, где я поступаю неправильно. Пожалуйста, направляйте меня. Я изменил setMaxConnectionsPerAddress (10) на setMaxConnectionsPerAddress (1) – raajaag

Смежные вопросы