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