两部android设备通过服务器转发实现通信简单demo

实现该通信的基本思路是:利用servlet服务器进行数据转发,利用android设备(手机)长连接本文已定时器来模拟长连接,实现了两部android手机内网通信。


1、作为终端的设备的设备主要是一个开机启动后就启动的一个服务,按照一定的时间间隔用http协议去请求服务器,查询服务器的状态,如果连接服务器,获得的相应是开启GPS信息收集,则在这个服务里开启已经安装在该android手机上的GPS信息收集APP,然后通过Http的GET方式源源不断的向服务器传递GPS信息。

关键代码如下:

public class RunningServiceByPowerOn extends Service {
	private SharedPreferences mPreferences;
	public RunningServiceByPowerOn() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		mPreferences=getSharedPreferences("Config",MODE_PRIVATE);
		 timerTaskforGpsSwitch();
	}
	
	/**
	 * 每隔5s查询一次
	 */
	private void timerTaskforGpsSwitch(){
		  Timer timer = new Timer();
		  Date d2 = new Date(System.currentTimeMillis());	
		  timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				Log.i("是否开启GPS收集","定时器开启");
				String spec="http://"+ConentValues.serverIp+":8080/MyServer/StartAction?mAction=find_gps_switcher1";
				URL url;
				 String str=null;
				try {
					url = new URL(spec);
					 str=HttpToServierUtils.connect(url);
					 if(str!=null&&str.equals("GPS_start")){
							//开启GPS服务
						 Log.i("是否开启GPS收集","开启GPS信息收集服务");
							//Toast.makeText(getApplicationContext(),"开启GPS信息收集服务",0).show();
						 //开启一个应用
						 if(mPreferences.getBoolean("isStop", true)){
							 Intent intent = new Intent(Intent.ACTION_MAIN);
							 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							 intent.addCategory(Intent.CATEGORY_LAUNCHER);            
							 ComponentName cn = new ComponentName("com.yqq.gpsinfolocationstartreceiver", "com.yqq.gpsinfolocationstartreceiver.MainActivity");            
							 intent.setComponent(cn);
							 startActivity(intent);
							 mPreferences.edit().putBoolean("isStop", false).commit();
						 }
						 
						
						}
					 if(str!=null&&str.equals("GPS_stop")){
						 mPreferences.edit().putBoolean("isStop",true).commit();
					 }
						
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			
				
			}
		},d2, 5000);
	}

}

Gps信息收集的关键代码:

public class GpsInfoCollectionService extends Service {
	
	private Boolean D=true;
	private GPSinfoDao mGpSinfoDao;
	private LocationManager mLocationManager;
	private Location mLocation;
	Criteria criteria;
	private String provider;
	public GpsInfoCollectionService() {
		
	}

	@Override
	public IBinder onBind(Intent intent) {
		if(D){
			Log.i("GPS服务数据收集","IBinder()");
		}
		return null;
	}
	@Override
	public void onCreate() {
		if(D){
			Log.i("GPS服务数据收集","onCreate()");
		}
		super.onCreate();
 mLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);  
 criteria = new Criteria();
 criteria.setAccuracy(Criteria.ACCURACY_FINE);//获取精确的位置.
 criteria.setAltitudeRequired(true);
 criteria.setBearingRequired(true);
 criteria.setCostAllowed(true);
 criteria.setPowerRequirement(Criteria.POWER_LOW);
 criteria.setSpeedRequired(true);
        //判断GPS是否正常启动  
        if(!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){  
            Toast.makeText(this, "请开启GPS导航...", Toast.LENGTH_SHORT).show();  
          
            //返回开启GPS导航设置界面  
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);   
		
	
        }
    	mGpSinfoDao=new GPSinfoDao(getApplicationContext());
    	timerTaskforGpsSwitch();
		
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if(D){
			Log.i("GPS服务数据收集","onStartCommand()");
		}
		  
	        
	         provider = mLocationManager.getBestProvider(criteria, true);
	         Log.i("<<<<",provider);
		
	     		
	        mLocationManager.requestLocationUpdates(provider, 300, 0.01f, new LocationListener() {
				
				@Override
				public void onStatusChanged(String provider, int status, Bundle extras) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onProviderEnabled(String provider) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onProviderDisabled(String provider) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onLocationChanged(Location location) {
					if(location==null){
						return;
					}
					//updateLocation(location);
					mLocation=location;
					new AsyncTask<Void, Void, Void>() {
						private String str=null;
						@Override
						protected Void doInBackground(Void... params) {
							
							String height=mLocation.getAltitude()+"";
							String longitude=mLocation.getLongitude()+"";
							String latitude=mLocation.getLatitude()+"";
							String name="Test";
							//http://172.22.122.1:8080/MyServer/MyTest?longitude=111&latitude=222&height=1000&name=Test
							//通过http向服务器传递数据
							String spec="http://"+ConentValues.serverIp+":8080/MyServer/MyTest?longitude="+longitude+"&latitude="+latitude+"&height="+height+"&name="+name;
							URL url;
							try {
								url = new URL(spec);
								 str=HttpToServierUtils.connect(url);
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						
							/*GpsInfo info=new GpsInfo();
								info.setLongitude(longitude+"");
								info.setLatitude(latitude+"");
								info.setHeight(height+"");
								mGpSinfoDao.addGpsInfo(info);
								info=null;*/
							return null;
						}
						@Override
						protected void onPostExecute(Void result) {
							
							
							Toast.makeText(getApplicationContext(), str,0).show();
							
						};
						
					}.execute();
	        
	    
				}
				
	        });
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		if(D){
			Log.i("GPS服务数据收集","onDestroy()");
		}
		mGpSinfoDao=null;
		mLocationManager=null;
		mLocation=null;
		super.onDestroy();
	}
	
	/**
	 * 每隔5s查询一次
	 */
	private void timerTaskforGpsSwitch(){
		  Timer timer = new Timer();
		  Date d2 = new Date(System.currentTimeMillis());	
		  timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				Log.i("终端信息收集","定时器开启");
				String spec="http://"+ConentValues.serverIp+":8080/MyServer/MyTest?mAction=find_gps_switcher";
				URL url;
				 String str=null;
				try {
					url = new URL(spec);
					 str=HttpToServierUtils.connect(url);
					/* if(str!=null&&str.equals("GPS_start")){
							//开启GPS服务
						 Log.i("终端信息收集","开启GPS信息收集服务");
							//Toast.makeText(getApplicationContext(),"开启GPS信息收集服务",0).show();
						}*/
						if(str!=null&&str.equals("GPS_stop")){
							Log.i("终端信息收集","停止GPS信息收集服务");
							//Toast.makeText(getApplicationContext(),"关闭GPS信息收集服务",0).show();
							//关闭GPS服务
							//getSharedPreferences("Config",MODE_PRIVATE).edit().putBoolean("isStarted", false).commit();
							stopSelf();
							System.exit(0);
							
						}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			
				
			}
		},d2, 5000);
	}

}

2、服务端利用servlet来处理各自的请求和响应

关键代码:

(1)处理GPS信息上传到服务器的servlet

public class MyTest extends HttpServlet {
	//private List<GpsInfo> infos;
	
	private GpsInfo info;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		resp.setCharacterEncoding("utf-8");
		PrintWriter  out=resp.getWriter();
		String nameAction=(String)req.getAttribute("nameAction");
		
		
		//String spec="http://"+ConentValues.serverIp+":8080/MyServer/MyTest?longitude="+longitude+"&latitude="+latitude+"&height="+height;			
		String longitude=req.getParameter("longitude");
		String latitude=req.getParameter("latitude");
		String height=req.getParameter("height");
		String name=req.getParameter("name");
		
		String mAction=req.getParameter("mAction");
		//查询服务器端数据库并获得返回值
		
		
	
		if(mAction!=null&&mAction.equals("find_gps_switcher")){
			System.out.println("定时器服务查询:"+mAction);
		try {
			
			String result=DbUtis.getGPSStaus();
			if(result!=null&&result.equals("start_gps")){
				out.write("GPS_start");
				out.flush();
			}
			if(result!=null&&result.equals("end_gps")){
				out.write("GPS_stop");
				out.flush();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
				
				
				
			
		}
		
		try {
			 //上传的服务器的数据
		
			
			
			if(longitude!=null&&latitude!=null&&height!=null){
				info=new GpsInfo();
				info.setLongitude(longitude);
				info.setLatitude(latitude);
				info.setHeight(height);
				info.setName(name);
				DbUtis.insertGpsInfos(info);
				System.out.println("游客终端上传的数据:"+info.toString());
				
				
			
			
			
				out.write("GPS数据已经上传到服务器");
				
				
				out.flush();
			}
			
				
			
				
			
			
	
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			/*if(out!=null){
				out.close();
			}*/
			
			
		}
		
	}

}

(2)
/**
 * 处理gps开关信息的servlet
 * @author yqq_coder
 *
 */
public class GpsOnOffAction extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//开启GPS收集
		String gpsSend=req.getParameter("namegpsend");
		//关闭GPS终端收集服务
		String gpsstop=req.getParameter("namegpsstop");
		PrintWriter out=resp.getWriter();
		//开启GPS收集
		if(gpsSend!=null&&gpsSend.equals("start_gps")){
			System.out.println("GPS信息收集指令:"+gpsSend);
			out.write("终端GPS信息收集开启");
			try {
				DbUtis.deleteGpsSatus();
				DbUtis.insertGpsSatus("start_gps");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// req.setAttribute("nameAction", "GPS_start");
			// req.getRequestDispatcher("/MyTest").forward(req, resp);  
		}else
		//关闭GPS终端收集服务
		if(gpsstop!=null&&gpsstop.equals("end_gps")){
			System.out.println("GPS信息关闭指令:"+gpsstop);
			out.write("终端GPS信息收集关闭");
			try {
				DbUtis.deleteGpsSatus();
				DbUtis.insertGpsSatus("end_gps");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			//req.setAttribute("nameAction", "GPS_stop");
			 //req.getRequestDispatcher("/MyTest").forward(req, resp);  
		}
		out.flush();
		
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
	doPost(req, resp);
	}
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.service(req, resp);
	}
	

}
/**
 * 查询GPS信息
 * @author yqq_coder
 *
 */
public class QurAction extends HttpServlet {
	private JSONArray infos;
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//轨迹显示参数
		String s = req.getParameter("namereq");
		PrintWriter out=resp.getWriter();
		//查询
		//http://172.22.122.1:8080/MyServer/MyTest?namereq=Test
		if(s!=null){
			
		 out=resp.getWriter();
			System.out.println(s);
			try {
				infos=DbUtis.getData(s);
				System.out.println("返回客户端的数据:"+infos.toString());
				
				out.write(infos.toString());
				
					
				out.flush();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				
				if(out!=null){
					out.close();
				}
			}
			
			
		}
		
	
		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	
	

}

/**
 * 处理是否开启GPS信息收集的servlet
 * @author yqq_coder
 *
 */
public class StartAction extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		resp.setCharacterEncoding("utf-8");
		PrintWriter  out=resp.getWriter();
		String nameAction=(String)req.getAttribute("nameAction");
		
		
		
		
		String mAction=req.getParameter("mAction");
		//查询服务器端数据库并获得返回值
		
		
	
		if(mAction!=null&&mAction.equals("find_gps_switcher1")){
			System.out.println("定时器服务查询:"+mAction);
		try {
			
			String result=DbUtis.getGPSStaus();
			if(result!=null&&result.equals("start_gps")){
				out.write("GPS_start");
				out.flush();
			}
			if(result!=null&&result.equals("end_gps")){
				out.write("GPS_stop");
				out.flush();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(out!=null){
				out.close();
		}
			
				
				
				
			
		}
		
		
		}
			
			
		
	}

}

数据库工具类:



import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;



import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;





public class DbUtis {
	private static String ip="192.168.1.134";
	private static Connection conn;

	public static JSONArray getData(String name) throws SQLException {
		List<GpsInfo> infos = new ArrayList<GpsInfo>();
		JSONArray array = new JSONArray();
		GpsInfo info = null;
		JSONObject jsonObject = null;
		PreparedStatement pstmt =null;
		ResultSet rs = null;
		// 连接数据库
		try {
			Class.forName("com.mysql.jdbc.Driver");
			// 链接数据库
			conn =   DriverManager.getConnection(
					"jdbc:mysql://"+ip+":3306/test", "root", "admin");
			// Statement stmt =(Statement) conn.prepareStatement("");
			String sql="select name,longitude,latitude from gpsinfos where name=?";
			pstmt=  conn.prepareStatement(sql);
			pstmt.setString(1, name);
			rs = pstmt.executeQuery();
			
			// 从结果集里取值
			//System.out.println(rs.getRow());
			while (rs.next()) {

				// info=new GpsInfo();
				// info.setLatitude(rs.getString(0));//纬度
				// info.setLongitude(rs.getString(1));
				// infos.add(info);
				// info=null;
				jsonObject = new JSONObject();
				try {
					jsonObject.put("name", rs.getString("name"));
					jsonObject.put("longitude", rs.getString("longitude"));
					jsonObject.put("latitude", rs.getString("latitude"));
					array.put(jsonObject);
					jsonObject=null;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 

			}
			

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if(pstmt!=null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		}

		return array;

	}
	
	public static String getGPSStaus() throws SQLException {
		String result=null;
		PreparedStatement pstmt =null;
		ResultSet rs = null;
		// 连接数据库
		try {
			Class.forName("com.mysql.jdbc.Driver");
			// 链接数据库
			conn =   DriverManager.getConnection(
					"jdbc:mysql://"+ip+":3306/test", "root", "admin");
			// Statement stmt =(Statement) conn.prepareStatement("");
			String sql="select gps_staus from gps_switcher ";
			pstmt=  conn.prepareStatement(sql);
			
			rs = pstmt.executeQuery();
			
			// 从结果集里取值
			//System.out.println(rs.getRow());
			while (rs.next()) {
				result=rs.getString("gps_staus");
				
			
			}
			
			
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if(pstmt!=null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		}

		return null;

	}
	
	
	public static void insertGpsInfos(GpsInfo info) throws SQLException{
		PreparedStatement pstmt = null; // 数据库表达式
	        ResultSet rs = null; // 结果集
	        try {
	            /*加载驱动*/
	        	//192.168.173.1
	            Class.forName("com.mysql.jdbc.Driver");
	            /*连接到数据库*/
	            conn =   DriverManager.getConnection(
	                    "jdbc:mysql://"+ip+":3306/test", "root", "admin");
	            String sql = "insert into gpsinfos (name,longitude,latitude) values (?,?,?)";
	            /* 获取表达式*/
	             pstmt =  conn.prepareStatement(sql);
	             pstmt.setString(1,info.getName());
	            pstmt.setString(2, info.getLongitude());
	            pstmt.setString(3, info.getLatitude());
	            /*  插入数据*/
	           pstmt.execute();
	            /* 执行SQL*/
	            rs = pstmt.executeQuery("select * from gpsinfos");
	            /* 查看里面的数据*/
	            while (rs.next()) {
	            	 System.out.println("插入的数据姓名=" + rs.getString("name"));
	                System.out.println("插入的数据经度=" + rs.getString("longitude"));
	                System.out.println("插入的数据纬度=" + rs.getString("latitude"));
	            }        
	        } catch (SQLException ex) {
	            ex.printStackTrace();
	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }finally{
	        	
	        	if(rs!=null){
	        		rs.close();
	        	}
	        	if(pstmt!=null)
				{
					pstmt.close();
					pstmt = null;
				}
	        	
	        	if(conn!=null){
	        		conn.close();
	        	}
	        	
	        	
	        }
	    }
		
	
      
	
	
	public static void insertGpsSatus(String staus) throws SQLException{
		PreparedStatement pstmt = null; // 数据库表达式
	        ResultSet rs = null; // 结果集
	        try {
	            /*加载驱动*/
	        	//192.168.173.1
	            Class.forName("com.mysql.jdbc.Driver");
	            /*连接到数据库*/
	            conn =   DriverManager.getConnection(
	                    "jdbc:mysql://"+ip+":3306/test", "root", "admin");
	            String sql = "insert into gps_switcher (gps_staus) values (?)";
	            /* 获取表达式*/
	             pstmt =  conn.prepareStatement(sql);
	             pstmt.setString(1,staus);
	           
	            /*  插入数据*/
	           pstmt.execute();
	            /* 执行SQL*/
	            rs = pstmt.executeQuery("select * from gps_switcher");
	            /* 查看里面的数据*/
	            while (rs.next()) {
	            	 System.out.println("插入的数据GPS状态=" + rs.getString("gps_staus"));
	              
	            }        
	        } catch (SQLException ex) {
	            ex.printStackTrace();
	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }finally{
	        	
	        	if(rs!=null){
	        		rs.close();
	        	}
	        	if(pstmt!=null)
				{
					pstmt.close();
					pstmt = null;
				}
	        	
	        	if(conn!=null){
	        		conn.close();
	        	}
	        	
	        	
	        }
	    }
		
	
	
	public static void deleteGpsSatus() throws SQLException{
		PreparedStatement pstmt = null; // 数据库表达式
	        ResultSet rs = null; // 结果集
	        try {
	            /*加载驱动*/
	        	//192.168.173.1
	            Class.forName("com.mysql.jdbc.Driver");
	            /*连接到数据库*/
	            conn =   DriverManager.getConnection(
	                    "jdbc:mysql://"+ip+":3306/test", "root", "admin");
	            String sql="delete from gps_switcher";  
	         
	             pstmt =  conn.prepareStatement(sql);
	           
	         
	          
	           pstmt.execute();
	          
	        } catch (SQLException ex) {
	            ex.printStackTrace();
	        } catch (Exception e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }finally{
	        	
	        	if(rs!=null){
	        		rs.close();
	        	}
	        	if(pstmt!=null)
				{
					pstmt.close();
					pstmt = null;
				}
	        	
	        	if(conn!=null){
	        		conn.close();
	        	}
	        	
	        	
	        }
	    }
		
	
	
	
	
	public static void createTable() throws SQLException{
		try {
			//Class.forName("com.mysql.jdbc.Driver");
			Connection conn =  DriverManager.getConnection("jdbc:mysql://"+ip+":3306/test","root","admin");

			String sql = "CREATE TABLE gpsinfos (id int primary key auto_increment, name varchar(64) not null, longitude varchar(256) not null , latitude varchar(256) not null );";
			//CREATE TABLE gpsinfos (id int primary key auto_increment, gps_staus varchar(16) not null)
			//gps_switcher(id int primary key auto_increment, gps_staus varchar(16) not null unique)
			PreparedStatement pstmt =  conn.prepareStatement(sql);
			pstmt.executeUpdate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	

	public static void main(String[]args) throws SQLException{
		/*
		try {
			createTable();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
		//insertGpsInfos(new GpsInfo("小强","5225.1111111","5333333.888222"));
		System.out.println(DbUtis.getData("Lihua"));
	}
}


控制端主要是发送几个GET方式的请求,这里就不再贴代码了。

几个请求:

"http://"+ConentValues.serverIp+":8080/MyServer/MyTest?mAction=find_gps_switcher";

"http://"+ConentValues.serverIp+":8080/MyServer/StartAction?mAction=find_gps_switcher1";

http://172.22.122.1:8080/MyServer/MyTest?longitude=111&latitude=222&height=1000&name=Test

http://172.22.122.1:8080/MyServer/MyTest?namereq=Test

demo下载地址:http://download.csdn.net/detail/u014600432/8209931


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这两天下了一个使用UDP传输目录内文件的程序,发出来给大家一起看看,共同进步。有问题请指教。 由于udp丢包比较厉害,因此使用了自定义的内部协议,进行双方的确认。 程序跑起来后,看网络状况,有时候会一卡一卡的。 以下是程序说明: * 本程序集成了数据导出端(服务器端)和数据导入端(客户端),使用UDP进行文件传递 * 服务器端的文件来源目录,见Tools中SOURCEPATH的设置 * 客户端的文件保存目录,见Tools中DESTINATIONPATH的设置,可以根据自己需要进行调整 * * 由于UDP存在丢包问题,因此Server和Client的通讯需要来回包进行确认,协议包头如下: * 1. "55 aa 99 01",表示客户端发起广播请求,请求服务器响应 * 2. "55 aa 99 02 + 服务器设备名称",表示服务器接收到广播后,响应客户端请求,把此包指定IP发送客户端(此指定IP地址可以UDP广播信息包中获取) * 3. "55 aa 99 03",表示客户端接收到服务器的响应,接着向服务器指定IP请求:需要传递的文件总数目和文件总容量(单位为KB) * 4. "55 aa 99 04 + 4字节文件总数目和4字节的文件总容量",表示服务器接收到客户端的0x03请求,统计SOURCEPATH中的所有文件数目和文件总容量,发送指定IP地址的客户端 * 5. "55 aa 99 05",客户端接收到文件总数目和文件总容量,请求服务器发送文件具体内容 * 6. "55 aa 99 10 + 文件名称",服务器发送文件名称 * 7. "55 aa 99 11",客户端响应,表示接收到服务器发送的0x10包 * 8. "55 aa 99 12+文件内容",服务器端发送具体文件内容 * 9. "55 aa 99 13",客户端响应,表示接收到服务器发送的0x12包 * 10."55 aa 99 14",服务端高速客户端发送完毕 * * 注意:服务器发送0x10包后,收到客户端的0x11响应包,将把文件具体内容拆分成N个0x12包,每个包的大小见Tools.byteSize的设置,目前设置为10K, * 服务器没收到一个0x13响应包,才能继续发下一个0x12包,已放置UDP的丢包,另外每个0x12包最多发送10次而无0x13包的响应,则发送进程结束,界面提示 * * 本程序已经封装好,调用见TransportFilesActivity.java文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值