2010-07-27 3 views
2

저는 안드로이드를 처음 사용하고 있으며, 안드로이드 응용 프로그램의 클라이언트 서버 (네트워크의 로컬 서버) 통신을위한 간단한 http 연결 코드가 필요합니다. 응용 프로그램이 시작될 때 연결이 시작되고 서버에서 업데이트해야하며 클라이언트에서 알림을 받아야하며 서버 응답은 클라이언트 요청을 기반으로해야합니다. 도와주세요. 감사은 안드로이드 응용 프로그램에서 서버 클라이언트 연결 코드가 필요합니다.

답변

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; 
    } 

} 

연결, 분리 :)

을 읽고 보내
관련 문제