tags:

views:

116

answers:

1

hi, i am new to android and need simple http connection codes for client server(local server in the network) communication in android application.the connection starts when the application is started and if there is any update in the server it should be notified on the client and the server response must be based on the client request. please help. thanks

+1  A: 
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;
  }

}

connect, send, read, disconnect :)

optimystery