2
我是android的新手,并且需要在android应用程序中为客户端服务器(网络中的本地服务器)通信提供简单的http连接代码。连接在应用程序启动时启动,并且如果有在服务器中更新它应在客户端上通知,并且服务器响应必须基于客户端请求。 请帮忙。 感谢在Android应用程序中需要服务器客户端连接代码
我是android的新手,并且需要在android应用程序中为客户端服务器(网络中的本地服务器)通信提供简单的http连接代码。连接在应用程序启动时启动,并且如果有在服务器中更新它应在客户端上通知,并且服务器响应必须基于客户端请求。 请帮忙。 感谢在Android应用程序中需要服务器客户端连接代码
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;
}
}
连接,发送,阅读,断开:)