2011-07-28 60 views
2

我是新來編程,我試圖建立一個黑莓IRC客戶端,我使它連接到服務器,加入一個頻道,並說些什麼,但我怎樣才能接收消息?我不知道如何建立一個等待消息的循環,有人能幫助我嗎?這裏是我的代碼:Java套接字和黑莓編程

package com.rim.samples.device.socketdemo; 

import java.io.*; 
import javax.microedition.io.*; 
import net.rim.device.api.ui.*; 

public class ConnectThread extends Thread 
{ 
    private InputStream _in; 
    private OutputStreamWriter _out;   
    private SocketDemoScreen _screen; 

    // Constructor 
    public ConnectThread() 
    { 
     _screen = ((SocketDemo)UiApplication.getUiApplication()).getScreen(); 
    } 

    public void run() 
    {   
     StreamConnection connection = null;  
     String user = "Cegooow"; 
     String channel = "#oi"; 

     try 
     { 
      _screen.updateDisplay("Opening Connection..."); 
      String url = "socket://" + _screen.getHostFieldText() + ":6667" + (_screen.isDirectTCP() ? ";deviceside=true" : "");          
      connection = (StreamConnection)Connector.open(url); 
      _screen.updateDisplay("Connection open"); 

      _in = connection.openInputStream(); 

      _out = new OutputStreamWriter(connection.openOutputStream());    
      StringBuffer s = new StringBuffer(); 

      _out.write("NICK " + _screen.getNickText() + "\r\n"); 
      _out.write("USER " + user + "8 * : Java Bot\r\n"); 
      _out.write("JOIN " + channel + "\r\n"); 
      _out.write("PRIVMSG " + channel + " " + _screen.getMessageFieldText() + "\r\n"); 
      _screen.updateDisplay("Done!"); 
     } 
     catch(IOException e) 
     { 
      System.err.println(e.toString()); 
     } 
     finally 
     {    
      _screen.setThreadRunning(false); 

      try 
      {    
       _in.close();    
      } 
      catch(IOException ioe) 
      {     
      } 
      try 
      {  
       _out.close();    
      } 
      catch(IOException ioe) 
      {    
      } 
      try 
      {    
       connection.close(); 
      } 
      catch(IOException ioe) 
      {     
      } 
     } 
    } 
} 

我使用的插座演示樣品上blackerry JRE,感謝

回答

0

在你的代碼有一個OutputStreamWriter _out寫入服務器,傳入的連接_in(InputStream的)未使用。你應該期望有任何傳入的數據... 我能想到的最簡單的例子是這樣的:

// process the inputstream after writing to _out - in single threaded app 
Reader reader = new InputStreamReader(_in); 
int data; 
while((data = reader.read()) != -1){ 
    System.out.println((char) data); // do something with the char 
} 
reader.close(); 

在實踐中,這將是最好使用一個BufferedReader。另外,如果你正在構建一個聊天應用程序,創建一個新的線程來處理傳入數據和另一個線程來傳出數據可能是有益的。

0

一旦你的輸入流讀取處理就可以循環下去,直到連接關閉

BufferedReader reader = new BufferedReader(_in); 
while(true) { 
    String line = reader.readLine(); 
    // do something... 
}