Socket

2个app之间通讯,app1中负责定位,app2中接受,2s传递一次(server不停的发送,client不停的接受)

1.server端代码

public class Server implements Runnable{ 
	private Preferences pre ;
	private Context context;
	private String latitude = "";
	private String longitude = "";

	public Server(Context context){
		this.context = context;
		pre = Preferences.getInstance(context);
	}

	private Play_Thread playThread = null;

	public void run() 
	{ 
		try {  
			ServerSocket ss= new ServerSocket(5000);
			while (true) {  
				Socket socket = ss.accept();  
				socket.setSoTimeout(5 * 1000);  
				detache(socket);
			}  
		} catch (Exception e) {  
			e.printStackTrace();  
		}  
	} 

	/**
	 * 分流
	 * @param socket
	 */
	public void detache(Socket socket){
		int type;
		try {
			type = receiveRequest(socket.getInputStream());

			switch (type) {				
			case SocketProtocol.TYPE_PLAYER:
				if(playThread == null){
					playThread = new Play_Thread(socket);
					playThread.start();
				}
				break;
			case SocketProtocol.TYPE_HTTPSYNC:
				break;
			case SocketProtocol.TYPE_USBSYNC:
				break;
			default:
				break;
			}

		} catch (Exception e) {
			if (socket != null)
				try {
					socket.close();
					socket = null;
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		}
	}
	/**
	 * 接收请求信息
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public int receiveRequest(InputStream in) throws Exception {  
		// 接收,解析请求  
		byte[] buf = new byte[4096];
		int ret = in.read(buf);  
		int type = Integer.parseInt((new String(buf)).substring(0, ret));  
		return type;  
	} 
	/**
	 * 返回请求要的信息
	 * @param out
	 * @param result
	 * @throws Exception
	 */
	public void sendRespnose(OutputStream out, String result) throws Exception {  
		MyLog.write("socketServer返回的数据:"+result);
		out.write(result.getBytes());  
		out.flush();  

	} 
	
	public class Play_Thread extends Thread{
		public Socket socket;
		public Play_Thread(Socket socket){
			this.socket = socket;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			// 1.接收并解析请求数据  
			String result = null;  
			try{
				while(true){
					latitude = pre.getStringPreference(Preferences.LATITUDE, "0");
					longitude = pre.getStringPreference(Preferences.LONGITUDE, "0");

					if(!"0".equals(latitude)&&!"0".equals(longitude)){
						result = latitude+"$"+longitude;
						// 2.生成并发送响应数据  
						sendRespnose(socket.getOutputStream(), result);  
					}
					

					Thread.sleep(2000);
				}
			} catch (Exception e) {  
				System.out.println("AbsServer通信失败");  
				e.printStackTrace();  
			} finally {  
				try {  
					// 3.断开连接  
					socket.close(); 
					socket = null;
					playThread = null;
				} catch (IOException e) {  
					e.printStackTrace();  
				}  
			}  
		}
	}


}

2.client端

public class SocketClient {

	public  String request(String params) {  
		Socket socket = null;  
		String object = null; 
		try {  
			// 1.连接服务器  
			String ip = InetAddress.getLocalHost().getHostAddress();// 服务器Ip地址  
			//	socket = new Socket("127.0.0.1", 5000);  
			socket = new Socket(ip, 5000);
			// 2.发送请求数据  
			sendRequest(socket.getOutputStream(), params);  
			socket.isInputShutdown();  
			MyLog.write("Client*****请求发送成功*****接收响应"+ip);
			while(true){
				// 3.接收并解析响应数据  

				object = receiveResponse(socket.getInputStream()); 

				getlaAndlong(object);
				Thread.sleep(2000);
			}


		} catch (Exception e) {  
			e.printStackTrace();  
		} finally {  
			if (null != socket) {  
				try {  
					// 4.断开连接  
					socket.close();  
				} catch (IOException e) {  
					e.printStackTrace();  
				}  
			}  
		}  
		// 5.返回接收的数据  
		return object;  
	}  

	/**
	 * 生成并发送请求数据 
	 * @param out
	 * @param params
	 * @throws Exception
	 */
	public static void sendRequest(OutputStream out, String params) throws Exception {  
		out.write(params.getBytes());  
		out.flush();  
	}  



	/**
	 * 接收并解析响应数据
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static  String receiveResponse (InputStream in) throws IOException   {   

		StringBuffer out = new StringBuffer();   
		byte[]  b = new byte[4096];   
		int n;  
		//		while ((n = in.read(b))!= 45){   
		//		while (true) {
		n = in.read(b);
		out.append(new String(b,0,n));  
		//		Log.i("String接受到的while",n+"");

		//			if (n <= 0)
		//				break;
		//		}  
		return  out.toString();   
	} 
	
	/**
	 * 获取经度和纬度
	 * @param str
	 */
	private void getlaAndlong(String str){
		MyLog.write("接收到的信息="+""+str);
		if(!str.contains("$"))
			return;
		String strs[] = str.split("\\$");
		
		  EventBus.getDefault().post(  
                  new ListenLbsEven(strs[0], strs[1]));  


	}

}

3.开启server

Thread desktopServerThread = new Thread(new Server(this)); 
        desktopServerThread.start(); 

4.开启client

new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				SocketClient client = new SocketClient();
				client.request(240+"");
			}
		}).start();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值