首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在android应用程序中需要服务器客户端连接代码

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

Stack Overflow用户
提问于 2010-07-27 20:23:09
回答 1查看 3.6K关注 0票数 2

我对安卓是新手,需要简单的客户端服务器(网络中的本地服务器)的http连接代码在安卓application.the连接开始时,应用程序启动,如果有任何更新,它应该通知在客户端和服务器的响应必须是基于客户端的请求。请帮帮忙。谢谢

EN

回答 1

Stack Overflow用户

发布于 2010-07-29 14:28:49

代码语言:javascript
运行
复制
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;
  }

}

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3343542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档