In Android development, socket-based communication must be non-blocking, thus requiring the asynchronous separation of reader and writer, and the need to monitor the status of the socket network,
Monitoring interface
Package Com.io.sockets;import Java.io.ioexception;import Java.net.socket;public interface socketstatuslistener{ public static final int status_open = 0x01<<0;public static final int status_close = 0x01<<1;public static fin Al int status_reset = 0x01<<2;public static final int status_pip_broken = 0x01<<3;public static final int STAT Us_unkown = 0x01<<4;public void onsocketstatuschanged (Socket socket,int status,ioexception e);}
Handler read and write processing control
package com.io.sockets;import java.io.ioexception;import java.net.socket;public class sockethandler implements socketstatuslistener {private socket socket=null; Private readertask reader;private writertask writer;public sockethandler (Socket SOCKET) throws ioexception {this.socket = socket;this.socket.settcpnodelay (true); Reader = new readertask (socket); Writer = new writertask (socket); O Nsocketstatuschanged (socket, status_open, null);} /** * sendmessage: (Here is a word describing the effect of this method). <br/> * todo (This method is described here for conditions – optional). <br/> */public void sendmessage (string msg) {writer.send (msg);} Public void listen (Boolean islisten) {Reader.startlistener (this);} Public void shutdown () {if (!socket.isclosed () &&socket.isconnected ()) {try { Writer.finish ();Reader.finish (); Socket.close ();} catch (ioexception e) {e.printstacktrace () onsocketstatuschanged (socket, status_ CLOSE,&NBSP;E);} finally{reader = null;writer = null; SYSTEM.OUT.PRINTLN ("Socket connection is OFF!! ");}}} @Overridepublic void onsocketstatuschanged (socket socket,int status, ioexception e) {switch (status) {case SocketStatusListener.STATUS_CLOSE:case Socketstatuslistener.status_reset:case socketstatuslistener.status_pip_broken:shutdown (); Break;default: Break;}}}
Read task
package com.io.sockets;import java.io.bufferedreader;import java.io.ioexception;import java.io.inputstreamreader;import java.net.socket;import java.net.socketexception;public class readertask extends thread{private socketstatuslistener socketstatuslistener; private bufferedreader bufferedreader;private socket socket;private boolean Listening;public readertask (Socket socket) throws IOException{bufferedReader = New bufferedreader (New inputstreamreader (Socket.getinputstream ())); this.socket = socket;} /** * finish: (Here is a word describing the effect of this method). <br/> * todo (This method is described here for conditions – optional) .< br/> * @throws ioexception * */public void finish () throws ioexception{listening = false;interrupt (); if (bufferedreader!=null && socket! =null) {if (Socket.isinputshuTdown ()) {socket.shutdowninput ();} Bufferedreader.close ();}} /* (non-javadoc) * @see java.lang.runnable#run () */@Overridepublic synchronized void run () {while (listening) {string readstr = null;try { while ((Readstr=bufferedreader.readline ())!=null) {System.err.println ("[Server]:" +readstr);}} catch (ioexception e) {listening = false;if (socketstatuslistener!=null) {int status = parsesocketstatus (e); Socketstatuslistener.onsocketstatuschanged (Socket, status, &NBSP;E);} E.printstacktrace (); return;//the terminating thread continues to run, you can also use Continue}}}private int parsesocketstatus (IOException e) {if (SocketException.class.isInstance (e)) {string msg = e.getlocalizedmessage (). Trim (); ("Connection reset". Equalsignorecase (msg)) {Return socketstatuslistener.status_reset;} Else if ("socket is closed". Equalsignorecase (msg)) {Return socketstatuslistenEr. Status_close;} Else if ("Broken pipe". Equalsignorecase (msg)) {Return socketstatuslistener.status_pip_broken;}} Return socketstatuslistener.status_unkown;} /** * listen: (Here is a word describing the effect of this method). <br/> * todo (This method is described here for conditions – optional) .< Br/> * */public void startlistener (SOCKETSTATUSLISTENER&NBSP;SSL) {listening = true;this.socketstatuslistener = ssl;start ();}}
Write task
package com.io.sockets;import java.io.bufferedwriter;import java.io.ioexception;import Java.io.outputstreamwriter;import java.net.socket;public class writertask extends Thread{private BufferedWriter bufferedWriter;private String msg = null; Private socket socket = null;public writertask (Socket socket) throws Ioexception {this.bufferedwriter = new bufferedwriter (New outputstreamwriter ( Socket.getoutputstream ())); this.socket = socket;} /** * finishtask: (Here is a word describing the effect of this method). <br/> * todo (This method is described here for conditions – optional). <br/> * @throws ioexception * */public void finish () Throws ioexception {if (bufferedwriter!=null && socket!=null) {if (! Socket.isoutputshutdown ()) {socket.shutdownoutput ();} Bufferedwriter.close ();}} /* (Non-javadoc) * @see java.lang.runnable#run () */@Overridepublic synchronized void run () {try {bufferedwriter.write (msg); Bufferedwriter.flush ();} catch (ioexception e) {e.printstacktrace ();}} Public void send (string msg) {this.msg = msg;new thread (this). Start ();}}
Server-Side Testing
Public class tcpsocketserver {public static void main (String[] args) { List<sockethandler> serverhandlers = new copyonwritearraylist<sockethandler> () ; Serversocket serversocket = null;try {serversocket = new serversocket (8090, &NBSP;5); while (true) {socket clientsocket = serversocket.accept (); if (clientsocket.isconnected ()) {sockethandler serverhandler = new sockethandler (Clientsocket); ServerHandlers.add ( Serverhandler); Serverhandler.listen (true); Serverhandler.sendmessage ("Host:" +serversocket.getinetaddress (). Gethostaddress () + "\ r \ n");/*while (True) {scanner sc = new scanner (System.in); String next = sc.nextline () + "\ r \ n";for (sockethandler scitem : Serverhandlers) {scitem.sendmessage (next);}} */}}} catch (ioexception e) {e.printstacktrace ();} Finally{try {for (sockethandler serverhandler : serverhandlers) {serverhandler.shutdown ();} Serverhandlers.clear (); Serversocket.close ();} catch (ioexception e) {e.printstacktrace ();}}}
Client Testing
public class Tcpsocketclient {public static void main (string[] args) {Sockethandler ClientHandler = null;try {Socket Clien Tsocket = new Socket ("localhost", 8090), clientsocket.setkeepalive (true); Clientsocket.settcpnodelay (true); if ( Clientsocket.isconnected ()) {ClientHandler = new Sockethandler (clientsocket); Clienthandler.listen (true); while (true) {Scanner sc = new Scanner (system.in); String next = sc.nextline () + "\ r \ n"; if (!clientsocket.isclosed ()) {clienthandler.sendmessage (next);} Else{break;}}}} catch (IOException e) {e.printstacktrace ();} Finally{clienthandler.shutdown ();}}}
Java socket read-write asynchronous detach