1. 程式人生 > >rmi穿越防火牆

rmi穿越防火牆

前段時間寫了一個全文檢索服務,用的是RMI遠端呼叫。在本機上寫好後,測試ok.但一部署到伺服器上就報找不到服務。在網上找了一大通:
原因如下:
    RMI除了註冊埠外,其通訊埠是伺服器隨機產生的,因此不容易穿過防火牆。

現將我在網上搜索到的解決方法公佈在這裡,給其它人需要的人一個方便。也給自己一個方便。
如果要扣分就扣吧。
一、普通解決:

Java程式碼 複製程式碼 收藏程式碼
  1. import java.rmi.server.*;   
  2. import java.io.*;   
  3. import java.net.*;   
  4. publicclass SMRMISocket extends RMISocketFactory {   
  5. public Socket createSocket(String host, int port)    
  6. throws IOException{   
  7. returnnew Socket(host,port);   
  8.     }   
  9. public ServerSocket createServerSocket(int port)    
  10. throws IOException {   
  11. if (port == 0)   
  12.             port = 2098;//不指定就隨機
  13. returnnew ServerSocket(port);   
  14.     }   
  15. }   
import java.rmi.server.*;
import java.io.*;
import java.net.*;
public class SMRMISocket extends RMISocketFactory {
    public Socket createSocket(String host, int port) 
        throws IOException{
        return new Socket(host,port);
    }
    public ServerSocket createServerSocket(int port) 
        throws IOException {
        if (port == 0)
            port = 2098;//不指定就隨機
        return new ServerSocket(port);
    }
} 



二、Spring中

Java程式碼 複製程式碼 收藏程式碼
  1.  <bean id="rmiSearchService"class="org.springframework.remoting.rmi.RmiServiceExporter">   
  2. <property name="serviceName" value="search"/><!-- 服務名稱 -->   
  3. <property name="service" ref="searchService"/>   
  4. <property name="serviceInterface" value="velcro.searchengine.ISearcher"
    />   
  5. <property name="registryPort" value="2098"/><!-- 埠 -->   
  6. <property name="servicePort" value="2098"/>><!--不指定就隨機 -->   
  7. </bean>