2014-01-29 62 views
1

我正在做一個NetBeans(Java)中的應用程序來打開套接字(Client)並與它交換信息。如何在Java(TelNet)中實現接收套接字的事件?

的辦法,我這樣做是:

final String HOST = "10.1.1.98";//"localhost"; 

final int PORT=1236; 

Socket sc; 

DataOutputStream message; 

public void initClient() 
{ 
    try 
{ 
     sc = new Socket(HOST , PORT); 
     message = new DataOutputStream(sc.getOutputStream()); 

    } 
    catch(Exception e) 
    { 
     System.out.println("Error: "+e.getMessage()); 
    } 
} 

如果服務器不斷髮送信息,我必須知道。一種方法是使用一個定時器,它可以持續運行下面的一段代碼:

message = new DataOutputStream(sc.getOutputStream()); 

但它效率不高。

我想創建一個事件,負責從服務器獲取數據,例如在C#中我用事件處理程序的:

ip = new TcpIp(ipAddress, port); 

ip.DataRead += new EventHandler<TramaEventArgs>(ip_DataRead); 

.... 

void ip_DataRead(object sender, TramaEventArgs e) 
{ 

} 

我如何在Java中做到這一點?

+0

閱讀關於多線程。 –

回答

0

「正確」的方式來做到非阻塞IO在Java中是使用NIO API,看起來特別是在java.nio.channels.AsynchronousSocketChannel,讓你寫這樣的代碼:

InetSocketAddress serverAddress = new InetSocketAddress(InetAddress.getByName("10.1.1.98"), 1236); 

AsynchronousSocketChannel clientSocketChannel = AsynchronousSocketChannel.open(); 
clientSocketChannel.connect(hostAddress).get(); 

ByteBuffer buffer = getBuffer(); 
clientSocketChannel.read(buffer, Void, new ReadHandler(buffer)); 

當處理程序類似這樣的:

public class ReadHandler implements CompletionHandler<Integer, Void> 
{ 
    private ByteBuffer buffer; 

    public ReadHandler(ByteBuffer buffer) 
    { 
    this.buffer = buffer; 
    } 

    public void completed(Integer read, Void attachment) 
    { 
    if (read < 0) 
    { 
     return; 
    } 

    //TODO: read buffer according to the number of bytes read and process accordingly. 
    } 

    public void failed(Throwable exc, Void attachment) 
    { 
    //TODO: handle exception. 
    } 
} 

這裏要注意的重要事情是:

  • 有可能你會爲r瀏覽不完整的消息,所以你需要處理。
  • 您應該儘可能少地處理ReadHandler,而不是傳遞每個完整的消息(根據您的要求可能傳遞給ExecutorService或某個內部隊列)。
+0

InetSocketAddress有問題: [鏈接](https://scontent-b-atl.xx.fbcdn.net/hphotos-ash3/1010799_10152182977347342_703327715_n.jpg) – user3249244