JAVA客户端向服务器发送消息并接受返回的数据 然后把返回的数据再发到服务器上 然后再把返回的数据发到服务器 这样的循环操作要怎么写啊 贴出代码求一个简单的指点啊望各位大神们各不吝赐教啊!!!!
try {
URL url = new URL("http://******/*****/*****?C=" + "s");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(8000);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.flush();
connection.getResponseCode();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Log.i("返回的数据是 ", response.toString());
try {
JSONObject obj = new JSONObject(response.toString());
JSONArray arr = obj.getJSONArray("info");
for (int i = 0; i < arr.length(); i++) {
JSONObject subObj = arr.getJSONObject(i);
String id = subObj.getString("id");
String name = subObj.getString("name");
String ver = subObj.getString("ver");
Log.i("解析后的数据 ", "id=" + id + ",name=" + name + ",ver=" + ver);
}
} catch (JSONException e) {//
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
使用socket通信
建立一个socket
public static void main(String[] args) {
ServerSocket s = null;
Socket socket = null;
System.out.println("server starting....");
try {
s = new ServerSocket(PORT);
//等待新请求、否则一直阻塞
while(true){
socket = s.accept();
System.out.println("socket:"+socket);
//一旦有客户端接入,就创建处理线程
new ServeOneJabbr(socket);
}
} catch (Exception e) {
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}finally{
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
线程处理
public class ServeOneJabbr extends Thread{
private Socket socket = null;
private DataInputStream br = null;
private DataOutputStream pw = null;
public ServeOneJabbr(Socket s){
socket = s;
try {
br = new DataInputStream(socket.getInputStream());
pw = new DataOutputStream(socket.getOutputStream());
start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
int empty_times = 0;
while(true){
//死循环里面写你的业务逻辑处理
}
}
}