/** * socket连接,客户端 * */ public class ClientService extends Service { private static final String TAG = "ClientService"; private static ClientService instance; private Socket mSocket; private BufferedReader mInput; private PrintWriter mOut; private String content = ""; private String mHost; public static ClientService getInstance () { if (instance == null) { instance = new ClientService(); } return instance; } public void setIp (String ip) { this.mHost = ip; } @Nullable @Override public IBinder onBind (Intent intent) { return null; } @Override public void onCreate () { super.onCreate(); instance = this; } /** * 连接调用方法 * 传入ip地址 * 开始连接 * */ public void conn (String host) { if (TextUtils.isEmpty(host)) return; mHost = host; Log.d(TAG, "开始连接"); new Thread(connRun).start(); } /** * 用于连接的线程 * */ private Runnable connRun = new Runnable() { @Override public void run () { Log.e(TAG, "conn:" + mHost); try { //服务器ip 端口号 mSocket = new Socket(mHost, 8000); mInput = new BufferedReader(new InputStreamReader(mSocket.getInputStream())); mOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true); } catch (IOException ex) { ex.printStackTrace(); Log.e(TAG, "login exception" + ex.getMessage()); } //启动线程,接收服务器发送过来的数据 new Thread(mHandlerMsg).start(); } }; public void sendMsg (final String msg) { Log.e(TAG, "给服务端发送消息 / " + (mOut == null)); if (mOut == null || TextUtils.isEmpty( msg) || mSocket == null || mSocket.isClosed() || !mSocket.isConnected() || mSocket.isOutputShutdown()) { Log.e(TAG, "给服务端发送消息失败:" + (mSocket == null) + " / closed:" + (mSocket.isClosed()) + " / connected:" + mSocket.isConnected() + " / isoutshutdown:" + mSocket.isOutputShutdown()); return; } new Thread(new Runnable() { @Override public void run () { try { mOut.println(msg); } catch (Exception e) { Log.e(TAG, "给服务端发送消息异常"); e.printStackTrace(); } } }).start(); } private Runnable mHandlerMsg = new Runnable() { @Override public void run () { try { //不断接收服务器传来的信息 while (true) { if (!mSocket.isClosed()) { if (mSocket.isConnected()) { if (!mSocket.isInputShutdown()) { content = ""; if ((content = mInput.readLine()) != null) { Log.e("ClientService", "接受信息msg:" + content); //处理信息 handlerServiceMsg(content); } else { } } } } } } catch (Exception e) { e.printStackTrace(); } } }; /** * 处理接受的信息 * */ public void handlerServiceMsg (String msg) { Log.d(TAG, "处理信息:"+msg); } }
【android 学习记录】socket客户端
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.