2010-07-27 71 views
2

我是android的新手,並且需要在android應用程序中爲客戶端服務器(網絡中的本地服務器)通信提供簡單的http連接代碼。連接在應用程序啓動時啓動,並且如果有在服務器中更新它應在客戶端上通知,並且服務器響應必須基於客戶端請求。 請幫忙。 感謝在Android應用程序中需要服務器客戶端連接代碼

回答

3
Socket socket; 
InputStream is; 
OutputStream os; 
String hostname; 
int port; 

public void connect() throws IOException { 
    socket = new Socket(hostname, port); 
    is = socket.getInputStream(); 
    os = socket.getOutputStream(); 
} 

public void send(String data) throws IOException { 
    if(socket != null && socket.isConnected()) { 
    os.write(data.getBytes()); 
    os.flush(); 
    } 
} 

public String read() throws IOException { 
    String rtn = null; 
    int ret; 
    byte buf[] = new byte[512]; 
    while((ret = is.read(buf)) != -1) { 
    rtn += new String(buf, 0, ret, "UTF-8"); 
    } 
    return rtn; 
} 

public void disconnect() throws IOException { 
    try { 
    is.close(); 
    os.close(); 
    socket.close(); 
    } finally { 
    is = null; 
    os = null; 
    socket = null; 
    } 

} 

連接,發送,閱讀,斷開:)

相關問題