Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/199.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
需要android应用程序中的服务器客户端连接代码吗_Android - Fatal编程技术网

需要android应用程序中的服务器客户端连接代码吗

需要android应用程序中的服务器客户端连接代码吗,android,Android,我是android新手,需要在android应用程序中为客户端-服务器(网络中的本地服务器)通信提供简单的http连接代码。连接在应用程序启动时启动,如果服务器中有任何更新,则应在客户端上通知,服务器响应必须基于客户端请求。 请帮忙。 谢谢 连接、发送、读取、断开连接:) Socket socket; InputStream is; OutputStream os; String hostname; int port; public void connect() throws IOExcept

我是android新手,需要在android应用程序中为客户端-服务器(网络中的本地服务器)通信提供简单的http连接代码。连接在应用程序启动时启动,如果服务器中有任何更新,则应在客户端上通知,服务器响应必须基于客户端请求。 请帮忙。 谢谢

连接、发送、读取、断开连接:)

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

}