首页 > 代码库 > 查找附近的人。

查找附近的人。

这次跟门子轩写了个查找附近的人,功能是使用同一软件的人可以将地理位置信息上传到服务器,其他人可通过查找的功能将指定距离内的人的相关信息(包括地理位置信息)查找出来。

其实没什么技术含量,整个工程中最核心的地方就是用到了百度地图提供的lbs接口,通过这个接口访问百度地图提供的数据库,可以实现对表的增删改查等命令,也可以精确的计算gps之间的距离。

工程分为服务器与客户端,客户端可以上传GPS信息,服务器可以通过上传的信息对数据库的GPS进行更新与添加,客户端可以通过发送GPS定位信息让服务器返回附近的人。

因为功能太少,所以就没写图形界面,效果如下:

技术分享

 

 服务器是用的socket,消息采用的是对象流传输,一共定义了三个消息,更新/添加GPS坐标(MsgSet)、查找附近的人(MsgFind)、服务器返回附近的人的数据(MsgFindRes),还有一个存储信息的People类;

相关代码:

发送get与post请求的HttpTools类:

技术分享
  1 package tools;  2   3 import java.io.BufferedReader;  4 import java.io.IOException;  5 import java.io.InputStreamReader;  6 import java.io.PrintWriter;  7 import java.net.URL;  8 import java.net.URLConnection;  9 import java.util.List; 10 import java.util.Map; 11  12 public class HttpTools { 13     public static String sendGet(String url,String...params){ 14         String result = ""; 15         BufferedReader in = null; 16         try { 17             String _url = url+"?"; 18             for(String param:params) 19                 _url=_url+param+"&"; 20             _url = _url.substring(0, _url.length()-1); 21             URL realUrl = new URL(_url); 22             URLConnection connection = realUrl.openConnection(); 23             connection.setRequestProperty("accept", "*/*"); 24             connection.setRequestProperty("connection", "Keep-Alive"); 25             connection.setRequestProperty("user-agent", 26                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 27             connection.connect(); 28             Map<String, List<String>> map = connection.getHeaderFields(); 29             for (String key : map.keySet()) { 30                 MLog.DebugLog(key + "--->" + map.get(key)); 31             } 32             in = new BufferedReader(new InputStreamReader( 33                     connection.getInputStream())); 34             String line; 35             while ((line = in.readLine()) != null) { 36                 result += line; 37             } 38  39         }catch(Exception e){ 40             MLog.DebugLogError("发送GET请求出现异常!" + e); 41             e.printStackTrace(); 42         }finally { 43             try { 44                 if (in != null) { 45                     in.close(); 46                 } 47             } catch (Exception e2) { 48                 e2.printStackTrace(); 49             } 50         } 51         return result; 52     } 53     public static String sendPost(String url, String...params) { 54         PrintWriter out = null; 55         BufferedReader in = null; 56         String result = ""; 57         try { 58             String param = ""; 59             for(String _param:params) 60                 param=param+_param+"&"; 61             param = param.substring(0, param.length()-1); 62             URL realUrl = new URL(url); 63             // 打开和URL之间的连接 64             URLConnection conn = realUrl.openConnection(); 65             // 设置通用的请求属性 66             conn.setRequestProperty("accept", "*/*"); 67             conn.setRequestProperty("connection", "Keep-Alive"); 68             conn.setRequestProperty("user-agent", 69                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 70             // 发送POST请求必须设置如下两行 71             conn.setDoOutput(true); 72             conn.setDoInput(true); 73             // 获取URLConnection对象对应的输出流 74             out = new PrintWriter(conn.getOutputStream()); 75             // 发送请求参数 76             out.print(param); 77             // flush输出流的缓冲 78             out.flush(); 79             // 定义BufferedReader输入流来读取URL的响应 80             in = new BufferedReader( 81                     new InputStreamReader(conn.getInputStream())); 82             String line; 83             while ((line = in.readLine()) != null) { 84                 result += line; 85             } 86         } catch (Exception e) { 87             MLog.DebugLogError("发送 POST 请求出现异常!"+e); 88             e.printStackTrace(); 89         } 90         //使用finally块来关闭输出流、输入流 91         finally{ 92             try{ 93                 if(out!=null){ 94                     out.close(); 95                 } 96                 if(in!=null){ 97                     in.close(); 98                 } 99             }100             catch(IOException ex){101                 ex.printStackTrace();102             }103         }104         return result;105     }    106 107 }
HttpTools

用于调试的日志类

技术分享
 1 package tools; 2  3 public class MLog { 4     private static boolean isDebug = true; 5     public static void DebugLog(String msg){ 6         if(!isDebug) 7             return; 8         System.out.println(msg); 9     }10     public static void DebugLogError(String msg){11         if(!isDebug)12             return;13         System.err.println(msg);14     }15 }
MLog

服务器线程类

技术分享
  1 package server;  2   3 import java.io.IOException;  4 import java.io.ObjectInputStream;  5 import java.io.ObjectOutputStream;  6 import java.net.Socket;  7 import java.util.List;  8   9 import msg.Messages; 10 import msg.MsgFind; 11 import msg.MsgFindRes; 12 import msg.MsgHead; 13 import msg.MsgSet; 14 import msg.People; 15  16 import org.json.JSONArray; 17 import org.json.JSONObject; 18  19 import tools.HttpTools; 20 import tools.MLog; 21  22 public class ServerThread extends Thread { 23     private Socket client; 24     private ObjectInputStream ois; 25     private ObjectOutputStream oos; 26     private boolean isConnect  = true; 27     public ServerThread(Socket client) { 28         // TODO Auto-generated constructor stub 29         this.client = client; 30         try { 31             ois = new ObjectInputStream(client.getInputStream()); 32             oos = new ObjectOutputStream(client.getOutputStream()); 33         } catch (IOException e) { 34             // TODO Auto-generated catch block 35             e.printStackTrace(); 36         } 37     } 38     @Override 39     public void run() { 40         // TODO Auto-generated method stub 41         super.run(); 42         while(isConnect){ 43             try { 44                 Object obj = ois.readObject(); 45                 dealMsg(obj); 46             } catch (ClassNotFoundException e) { 47                 // TODO Auto-generated catch block 48                 e.printStackTrace(); 49             } catch (IOException e) { 50                 // TODO Auto-generated catch block 51                 e.printStackTrace(); 52                 isConnect = false; 53             } 54         } 55     } 56     private void dealMsg(Object obj) { 57         // TODO Auto-generated method stub 58         MsgHead mh = null; 59         try{ 60                 mh = (MsgHead)obj; 61         }catch(Exception e){ 62                 MLog.DebugLogError("收到了错误的包:"+obj.getClass().getName()); 63                 return; 64         } 65             switch (mh.getType()) { 66             case Messages.FindPeople: 67                 findPeople((MsgFind)mh); 68                 break; 69             case Messages.SetPeople: 70                 setPeople((MsgSet)mh); 71                 break; 72             default: 73                 MLog.DebugLogError("未知类型:"+mh.getType()); 74                 break; 75             } 76          77     } 78     private void setPeople(MsgSet obj) { 79         // TODO Auto-generated method stub 80         String result = HttpTools.sendGet(ServerMessage.FindUrl2,"ak="+ServerMessage.LbsKey, 81                                                                                                   "geotable_id="+ServerMessage.id, 82                                                                                                   "name="+obj.getName()); 83         System.err.println(result); 84         JSONObject json = new JSONObject(result); 85         try{ 86         JSONArray peoples = json.getJSONArray("pois"); 87         }catch(Exception e){ 88             HttpTools.sendPost(ServerMessage.createUrl,"ak="+ServerMessage.LbsKey, 89                      "geotable_id="+ServerMessage.id, 90                      "longitude="+obj.getLongitude(), 91                      "latitude="+obj.getLatitude(), 92                      "coord_type=1", 93                      "name="+obj.getName()); 94             return; 95         } 96          97         HttpTools.sendPost(ServerMessage.updateUrl, "ak="+ServerMessage.LbsKey, 98                                                                                 "geotable_id="+ServerMessage.id, 99                                                                                 "coord_type=1",100                                                                                 "name="+obj.getName(),101                                                                                 "longitude="+obj.getLongitude(),102                                                                                 "latitude="+obj.getLatitude());103     }104     private void findPeople(MsgFind obj) {105         // TODO Auto-generated method stub106         107         String result=HttpTools.sendGet(ServerMessage.FindUrl,"ak="+ServerMessage.LbsKey,108                                                                                        "geotable_id="+ServerMessage.id,109                                                                                        "location="+obj.getLongitude()+","+obj.getLatitude(),110                                                                                        "radius="+obj.getDistance(),111                                                                                              "sortby=distance:1");112         JSONObject json = new JSONObject(result);113         JSONArray peoples = json.getJSONArray("contents");114         MsgFindRes mfr = new MsgFindRes();115         List list = mfr.getPeoples();116         for(int i = 0;i<peoples.length();i++){117             JSONObject jo = peoples.getJSONObject(i);118             People p = new People();119             JSONArray ja = jo.getJSONArray("location");120             /*String location = jo.getString("location");121             location = location.replaceAll("[", "");122             location = location.replaceAll("]", "");123             location = location.replaceAll(" ", "");124             String str[] = location.split(",");125             p.setLongitude(Double.parseDouble(str[0]));126             p.setLatitude(Double.parseDouble(str[1]));*/127             p.setLongitude(ja.getDouble(0));128             p.setLatitude(ja.getDouble(1));129             p.setName(jo.getString("name"));130             p.setDirection(jo.getString("direction"));131             p.setDistance(jo.getInt("distance"));132             p.setAddress(jo.getString("province")+jo.getString("city")+jo.getString("district"));133             list.add(p);134         }135         try {136             oos.writeObject(mfr);137             oos.flush();138         } catch (IOException e) {139             // TODO Auto-generated catch block140             e.printStackTrace();141         }142     }143     144 }
ServerThread

服务器类

技术分享
 1 package server; 2  3 import java.io.IOException; 4 import java.net.ServerSocket; 5 import java.net.Socket; 6 import java.util.concurrent.ExecutorService; 7 import java.util.concurrent.Executors; 8  9 public class Server extends Thread{10     ServerSocket ss;11     ExecutorService es = Executors.newCachedThreadPool();12     @Override13     public void run() {14         // TODO Auto-generated method stub15         super.run();16         try {17             ss = new ServerSocket(ServerMessage.port);18             while(true){19             Socket socket = ss.accept();20             es.execute(new ServerThread(socket));21             }22         } catch (IOException e) {23             // TODO Auto-generated catch block24             e.printStackTrace();25         }26     }27 }
Server

  客户端类

技术分享
 1 package client; 2  3 import java.io.IOException; 4 import java.io.ObjectInputStream; 5 import java.io.ObjectOutputStream; 6 import java.net.Socket; 7 import java.net.UnknownHostException; 8  9 import msg.Messages;10 import msg.MsgFindRes;11 import msg.MsgHead;12 import msg.People;13 import server.ServerMessage;14 import tools.MLog;15 16 public class Client extends Thread{17     private static Client client;18     Socket socket;19     ObjectOutputStream oos;20     ObjectInputStream ois;21     boolean isConnect = true;22     private Client(){init();}23     public static Client getInstance(){24         client = client==null?new Client():client;25         return client;26     }27     public void sendMsg(MsgHead mh) throws IOException{28         oos.writeObject(mh);29         oos.flush();30     }31     private void init() {32         // TODO Auto-generated method stub33         try {34             Socket socket = new Socket(ServerMessage.ip, ServerMessage.port);35             oos = new ObjectOutputStream(socket.getOutputStream());36             ois = new ObjectInputStream(socket.getInputStream());37         } catch (UnknownHostException e) {38             // TODO Auto-generated catch block39             isConnect = false;40             e.printStackTrace();41         } catch (IOException e) {42             // TODO Auto-generated catch block43             isConnect = false;44             e.printStackTrace();45         }46         this.start();47     }48     public void run() {49         while(isConnect){50             try {51                 Object obj = ois.readObject();52                 dealMsg(obj);53             } catch (ClassNotFoundException e) {54                 // TODO Auto-generated catch block55                 e.printStackTrace();56             } catch (IOException e) {57                 // TODO Auto-generated catch block58                 e.printStackTrace();59                 isConnect = false;60             }61         }62         63     }64     private void dealMsg(Object obj) {65         // TODO Auto-generated method stub66         MsgHead mh = null;67         try{68             mh = (MsgHead)obj;69         }catch(Exception e){70             MLog.DebugLogError("类型转换异常:"+obj.getClass().getName());71             return;72         }73         switch (mh.getType()) {74         case Messages.FindRes:75             FindRes((MsgFindRes)mh);76             break;77 78         default:79             break;80         }81     }82     private void FindRes(MsgFindRes mh) {83         // TODO Auto-generated method stub84         int n = mh.getPeoples().size();85         MLog.DebugLog("共找到"+n+"个附近的人");86         for(People p : mh.getPeoples()){87             String str = "姓名:"+p.getName()+"\t地址:"+p.getAddress()+"\t距离:"+p.getDistance()+"米\t方向:"+p.getDirection()+"\t经纬度:"+p.getLongitude()+","+p.getLatitude();88             MLog.DebugLog(str);89         }90     };91 }
Client

消息类与一些常量就不贴了。

因为调用百度地图接口的时候需要收到json数据,所以还使用了org.json包。

没什么具体约定的规范,在编写的时候想起来缺少什么就现往里添加,及时补充。

从下午1点做到4点多钟。

心得与体会:

很多东西 可以直接利用现成的接口,因为自己写的并不一定比那些已经被验证了无数次的代码效果要好。很多事情还得现从实际生活中挖掘,加上之前已经有过类似的网络编程经验,所以做起来还算是得心应手。

技术分享

 

查找附近的人。