2013-11-09 114 views
0

我已經在OSGi中使用套接字完成了一個客戶端服務器模型。我在服務器端有一個bundle,我的activator類調用一個創建套接字並從客戶端獲取String數據的線程。現在我想從服務器端調用服務,以便我可以發送該字符串進行一些處理。我如何去做這件事?通過服務器線程調用OSGi服務

這是在服務器端

int serverport=5000; 
    Thread t; 
    public void start(BundleContext bundleContext) throws Exception { 
     Activator.context = bundleContext; 
     t = new StdServer(serverport,this); 
     t.start(); 

的StdServer類我Activator類將擴展處理該套接字創建一個線程。我想在激活器的啓動功能中調用一個服務。任何幫助深表謝意。

+0

看看遠程服務http://r-osgi.sourceforge.net/ – Mirco

回答

0

您可以通過getService()獲得服務參考,並將其作爲新線程的構造函數參數。

+0

感謝Areo。我發送了一個Activator對象給線程的構造函數,通過這個,我可以獲得服務引用和服務對象。 – sdwaraki

1

如果我正在讀你,那麼你仍然在服務器端的OSGi環境中,以及在同一個容器中運行的服務(如Karaf)。用你的激活器,你可以在上下文中得到它,你試過嗎?

另一種使用Bnd Annotations的方法也需要聲明性服務安裝在您的容器中。然後使用BND註解,你可以註釋一個類像這樣在「@Reference」將讓你從容器中需要的服務:

import java.util.Map; 

import org.osgi.framework.BundleContext; 

import aQute.bnd.annotation.component.Activate; 
import aQute.bnd.annotation.component.Component; 
import aQute.bnd.annotation.component.Deactivate; 
import aQute.bnd.annotation.component.Reference; 

//Doesn't have to be called Activator 
@Component 
public class Activator { 
    private BundleContext context; 
    private TheServiceINeed theServiceINeed; 

@Activate 
public void Activate(BundleContext context, Map<String, Object> props) { 
this.context = context; 

} 

@Deactivate 
public void Deactivate() { 
    this.context = null; 
} 

public TheServiceINeed getTheServiceINeed() { 
    return theServiceINeed; 
} 

    //The Service to process my String 
@Reference 
public void setTheServiceINeed(TheServiceINeed theServiceINeed) { 
    this.theServiceINeed = theServiceINeed; 
    } 

} 

是否使用BndTools與做你的工作?如果你問我,對於OSGi Development來說非常方便。

+0

非常感謝Tony的回覆。我使用getContext函數來獲取上下文並通過它獲得服務引用對象。 – sdwaraki

+0

YOu先生。我很高興它爲你解決。 – Tony