客户端:
@SuppressWarnings("rawtypes")
public Map getData(JSONObject json,Map<String, String> msg){
Map dataMaps = new HashMap();
Socket socket;
try{
String host = json.getString("host") ;
int port = Integer.parseInt(json.getString("port"));
socket = new Socket(host,port);
/** 发送客户端准备传输的信息 */
// 由Socket对象得到输出流,并构造PrintWriter对象
PrintWriter printWriter =new PrintWriter(socket.getOutputStream(),true);
// 将字符串输出到Server
printWriter.println(msg.get("cityCode")+";"+msg.get("day"));
socket.shutdownOutput();
// 用于获取服务端传输来的信息
// 由Socket对象得到输入流,并构造相应的BufferedReader对象
// 输入读入一字符串
InputStreamReader reader = new InputStreamReader(socket.getInputStream());
BufferedReader buffer = new BufferedReader(reader);
String readerData = buffer.readLine();
/** 关闭Socket*/
printWriter.close();
reader.close();
socket.close();
dataMaps = com.alibaba.fastjson.JSON.parseObject(readerData, Map.class);
}catch(Exception e){
String errorMsg = "Socket:"+e.getMessage();
log.addLog(errorMsg);
//TODO redis存失败任务
PutErrorMsgHandle putError = new PutErrorMsgHandle();
putError.putErrorMsg(msg, errorMsg);
}finally{
if(socket != null){
socket.close();
}
}
return dataMaps;
}
服务器端:
public class StatisticsRevMsgHandle extends SocketThread {
@Override
protected void execute(Socket client) {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
OutputStream os = null;
PrintWriter pw = null;
try{
System.out.print(DateTimeUtil.getNow()+": ");
//3、获取输入流,并读取客户端信息
is = client.getInputStream();
isr =new InputStreamReader(is);
br =new BufferedReader(isr);
String data = "";
String cityCode = "";
String statisticsDate = "";
while((data=br.readLine())!= null){
System.out.println(data);
String[] strs = data.split(";");
cityCode = strs[0];
statisticsDate = strs[1];
}
client.shutdownInput();//关闭输入流
//4、获取输出流,响应客户端的请求
os = client.getOutputStream();
pw = new PrintWriter(os);
ResStatisticsData rtnData = new ResStatisticsData();
String resdata = rtnData.sendData(cityCode, statisticsDate);
//获取Socket的输出流,用来向客户端发送数据
pw.write(resdata);
pw.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
//5、关闭资源
try {
if (pw != null)
pw.close();
if (os != null)
os.close();
if (br != null)
br.close();
if (isr != null)
isr.close();
if (is != null)
is.close();
if (client != null)
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}