Android之socket服务端

 

 

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;

@SuppressLint("NewApi")
public class SocketTCPServer implements Runnable
{      
    private String tag="SocketTCPServer";  
    //服务器端口
    private  final int SERVERPORT = 5111; 
    //存储所有客户端Socket连接对象
    public   List<Socket> mClientList = new ArrayList<Socket>(); 
    //线程池
    private ExecutorService mExecutorService;  
    //ServerSocket对象
    private ServerSocket mServerSocket;  
    private  PrintWriter mPrintWriter;
    private  String  mStrMSG;
    public SocketTCPServer()
    {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
        StartServer();
        handler.postDelayed(runnable, DELYED); //启动定时器
    }
  //接收线程发送过来信息,并用TextView显示
    public  Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            
            Log.e(tag,mStrMSG);
              
        }
    }; 
    //每个客户端单独开启一个线程
    class ThreadServer implements Runnable
    {
        private Socket mSocket;
        private DataInputStream dinput;
        public ThreadServer(Socket socket) 
        {
            try{
                this.mSocket = socket;
                dinput = new DataInputStream(socket.getInputStream());
                SendToClient("hello,tcp server...");
            }
            catch(Exception e){
                Log.e(tag, e.toString());
            }
            
        }
        public void run()
        {
            try
            {
                byte[] bbuf = new byte[10000];
                while (true) {
                    
                    if (!mSocket.isClosed()) {
                        if (mSocket.isConnected()) {
                            if (!mSocket.isInputShutdown()) {
                                int length = dinput.read(bbuf);
                                   mStrMSG = new String(bbuf, 0, length, "gb2312");
                                   mStrMSG += "\n";
                                   Log.e(tag, mStrMSG);
                                   mHandler.sendMessage(mHandler.obtainMessage());
                            }
                        }
                    }
                }
            }
            catch (IOException e)
            {
                Log.e(tag, e.toString());
            }
        }
    }
    public void run() {
        Socket client = null;
        try{
            while (true)
            {
                Log.e(tag, "收到客户端连接。。。");
                //接收客户连接并添加到list中
                client = mServerSocket.accept(); 
                mClientList.add(client);
                //开启一个客户端线程
                if(client!=null){
                    //异常捕不到,客户端退出后,程序挂了
                    mExecutorService.execute(new ThreadServer(client));
                }
                
            }
        }
        catch(Exception e){
            mClientList.remove(client);
            Log.e(tag, e.toString());
        }
    }
    /**
     * 向客户端发送消息
     * @param msg
     */
    public  void SendToClient(String msg){
        try{
            if(mClientList.size()>0){
                for (Socket client : mClientList)
                {
                    mPrintWriter = new PrintWriter(client.getOutputStream(), true);
                    mPrintWriter.println(msg);
                }
            }
        }
        catch(Exception e){
            Log.e("向客户端发送消息败了", e.toString());
            StartServer();//消息发送失败,重启服务器
        }
    }
    public void StartServer(){
        try
        {
            if(mServerSocket!=null){
                mServerSocket.close();
            }
            //设置服务器端口
            mServerSocket = new ServerSocket(SERVERPORT);
            //创建一个线程池
            mExecutorService = Executors.newCachedThreadPool();
            //用来临时保存客户端连接的Socket对象
            new Thread(SocketTCPServer.this).start();
        }
        catch (IOException e)
        {
            Log.e(tag, e.toString());
        }
        
    }
    public  void CloseServer(){
        try {
            mServerSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //定時器
    private int DELYED= 5000;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                handler.postDelayed(this, DELYED);
                SendToClient("this message from server:dongdongdong");
            } catch (Exception e) {
                Log.e(tag+"->runnable定时器", e.toString());
            }
        }
    };
}

 

 

客户端

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import com.onesuncomm.model.CurrentUserInfo;
import com.onesuncomm.utils.DateUtil;
import com.onesuncomm.w511.MainActivity;
import com.onesuncomm.w511.TabCorePlateLocateActivity;
import com.onesuncomm.w511.TabServerLogActivity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;

@SuppressLint("NewApi")
public class SocketTCPClient  implements Runnable {
    private static SocketTCPClient mobileSocket;
    private static String Tag="SocketTCPClient";

    private Socket socket = null;
    private BufferedReader in = null;
    private PrintWriter out = null;
    private String content = "";
    public SocketTCPClient(){
        try {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
            handler.postDelayed(runnable, DELYED); //启动定时器

        } catch (Exception ex) {
            Log.e(Tag+"->SocketTCPClient", ex.getMessage());
            CurrentUserInfo.SocketStatus=false;
        }
    }
    public static final SocketTCPClient instanceMobileSocket(){
        synchronized (SocketTCPClient.class) {
            if(mobileSocket==null) {
                mobileSocket = new SocketTCPClient();
            }
        }
        return mobileSocket;
    }
    public  void  ConnectionService(){
        try {
            
            if(socket!=null){
                socket.close();
            }
            socket = new Socket(CurrentUserInfo.server_ip, Integer.parseInt(CurrentUserInfo.server_port));
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                    socket.getOutputStream())), true);
            CurrentUserInfo.SocketStatus=true;
            //启动线程,接收服务器发送过来的数据
            new Thread(SocketTCPClient.this).start();
        } 
        catch (IOException ex) {
            CurrentUserInfo.SocketStatus=false;
        }
    }
    //接收线程发送过来信息
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //处理接收的信息
            TabServerLogActivity.AddToLog("接收("+DateUtil.GetNowDateString()+"):"+content);
            if(content.contains("Z0")){
                sendMsgToServer("Z0\r\n");
            }
            if(MainActivity.isNetworkAvailable()){
                //todo:  若返回lac,Cell则从服务器查询基站信息并显示在地图上
            }
            else{
                
            }
            //CurrentUserInfo.sbLog.append(content);
        }
    };
    /*
     * 读取服务器发来的信息,并通过Handler发给UI线程
     */
    public void run() {
        try {
            char [] bbuf = new char[10000];
            StringBuilder temp = new StringBuilder();
            while (true) {
                if (!socket.isClosed()) {
                    if (socket.isConnected()) {
                        CurrentUserInfo.SocketStatus=true;
                        timeOut=0;
                        if (!socket.isInputShutdown()) {
                            int leng=in.read(bbuf);
                            content  = new String(bbuf, 0, leng);
                            temp.append(content);
                            //if (temp.toString().contains("Z")){
                                content=temp.toString();
                                temp =new StringBuilder(); 
                                mHandler.sendMessage(mHandler.obtainMessage());
                            //}
                            CurrentUserInfo.SocketStatus=true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            CurrentUserInfo.SocketStatus=false;
            Log.e(Tag+"->run()", e.getMessage());
        }
    }

    public void sendMsgToServer(Object msg){
        if (socket.isConnected()) {
            if (!socket.isOutputShutdown()) {
                out.println(msg);
                TabServerLogActivity.AddToLog("发送("+DateUtil.GetNowDateString()+"):"+msg);
            }
        }
    }
    //定時器
    private int DELYED= 1000;
    private int timeOut=0;
    private int timeSendZ3=0;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                handler.postDelayed(this, DELYED);
                timeOut++;
                timeSendZ3++;
                if (socket==null||socket.isOutputShutdown()||!CurrentUserInfo.SocketStatus||!socket.isConnected()) {
                    CurrentUserInfo.SocketStatus=false;
                    new Thread() {
                    public void run() {
                        ConnectionService(); 
                    };
                    }.start();
                }
                
                TabCorePlateLocateActivity.setSocketStatus();
                
                
            } catch (Exception e) {
                Log.e(Tag+"->runnable定时器", e.toString());
            }
        }
    };
}

调用

/**
     * 开启socket
     */
    private void openSocket(){
        try{
            //SocketTCPServer server =new SocketTCPServer();
            //server.SendToClient("本消息来自服务器");
            final SocketTCPClient tcp =SocketTCPClient.instanceMobileSocket();
            new Thread() {
                public void run() {
                    tcp.ConnectionService();
                };
            }.start();
        }
        catch(Exception ex){
            LogUtil.WriteError(ex);
        }
    }

 

posted @ 2015-09-21 11:29  黄忠  阅读(1722)  评论(0编辑  收藏  举报