Android之Socket,Service通讯

本文介绍了Android中使用Socket进行服务器通讯的基本原理和特点,包括数据丢失率低、简单易移植等。通过示例代码展示了如何创建ServerSocket接收客户端数据,以及客户端如何指定服务器IP和端口进行连接并发送数据。项目结构包括IMService、MessageWorker和MainActivity等关键组件,后续文章将讲解服务端代码和客户端对接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                           Android与服务器之间的通讯方式主要有两种。一种是Http通讯 , 一种是Socket通讯。两者最大的差异在于,Http连接使用的是“请求---响应方式”,即在请求是建立连接通道,当客户端向服务器发送请求后,服务器端才能向客户端返回数据。而Socket则是在双方建立连接后就直接进行数据传输,在连接时可实现信息的主动推送,而不需要每次由客户端向服务端发送请求。 

                 

                 什么是Socket?又称套接字,是一种抽象层。在程序内部提供了与外界通讯的端口,即端口信息。通过建立Socket连接,可为通讯双方的传输提供通道。Socket的主要特点有数据丢失率低,使用简单且易于移植。

                   

                   本案例是基于TCP协议的Socket。服务端首先声明一个ServerSocket对象并且指定端口号。然后调用ServerSocket的accept()方法接收客户端的数据。accept()方法在没有数据进行接收的处于堵塞状态。(Socketsocket=serversocket.accept()),一旦接收到数据,通过inputstream读取接收的数据。


                     客户端创建一个Socket对象,指定服务器端的ip地址和端口号(Socketsocket=newSocket("172.168.10.108",8080);),通过inputstream读取数据,获取服务器发出的数据(OutputStreamoutputstream=socket.getOutputStream()),最后将要发送的数据写入到outputstream即可进行TCP协议的socket数据传输。

             项目结构:

                     

                      2. IMService.class                         

public class IMService extends Service {
	static Communication communication;
	public static String messageTag="com.gys.im.CYEJIMActivity";
	public static Notification notification;
	public static int messageId = 10000;
	private NotificationManager mNM;
	boolean isconnected;
	Timer timer=new Timer();
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
        communication=Communication.newInstance();
        communication.setReceiver(this);
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notification=new Notification(R.drawable.ic_launcher, "", System.currentTimeMillis());
        notification.number=1;
        timer.schedule(timerTask, 1000, 2000);
		
	}
	
    public Handler handler= new Handler()
    {
    	public void handleMessage(Message msg) {
    		String message=msg.obj.toString();
    		if(message.equals("start\n"))
    		{
    			start_check_in();
    		}else
    		{
    			Intent intent = new Intent(messageTag);
    			intent.putExtra("message", message);
    			IMService.this.sendBroadcast(intent);
    		}
    	}
    };
    
    public TimerTask timerTask=new TimerTask()
    {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			isconnected=checkNetwork();
			if(!isconnected)
			{
				showNotification("","");
			}
		}
    	
    };
    
    /**
     * 添加内容到发送消息队列
     * @param str
     */
    public static void addPacket(String str)
    {
    	communication.addPacket(str);
    }
    
    public static void wakeUp()
    {
    	communication.wakeUp();
    }
    
    /**
     * 开始发送心跳
     */
    protected void start_check_in()
    {
    	communication.start_check_in();
    }
    
	public  boolean checkNetwork() {
		boolean flag = false;
		ConnectivityManager cwjManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cwjManager.getActiveNetworkInfo() != null)
		{
			flag = cwjManager.getActiveNetworkInfo().isAvailable();
		}
		return flag;
	}
	
    private void showNotification(String statusInfo,String messageContent) {
        PendingIntent contentIntent = PendingIntent.getActivity(this,0,null,0);
        
        	notification.when=System.currentTimeMillis();
        	notification.tickerText=statusInfo;
            notification.setLatestEventInfo(this,"test",messageContent, null);
            notification.contentIntent=contentIntent;
            notification.vibrate = new long[] {100, 250, 100, 500};
            messageNotificationAdd(messageId, notification);
    }
    
    /*add a nonotification*/
    public void messageNotificationAdd(int notificationNo,Notification notification){
    	try
    	{
    		mNM.notify(notificationNo,notification);
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    	notification.number++;//number 增加后,可以与以前的notification区分开来
    }

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mNM.cancel(messageId);
	}

	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
	}

	@Override
	public boolean onUnbind(Intent intent) {
		// TODO Auto-generated method stub
		return super.onUnbind(intent);
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
}

                3.Communication.class :

public class Communication {

	private NetTransportWorker transportWorker;
	private MessageWo
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值