1. First write the Server:
public class SocketServer { private static Socket mSocket; public static void main(String[] argc) { try { //1. Create a server-side Socket, namely ServerSocket, specify the bound port, and listen for this port ServerSocket serverSocket = new ServerSocket(12345); InetAddress address = (); String ip = (); //2. Call accept() to wait for the client to connect ("~~~The server is ready, waiting for the client to access~, the server IP address: " + ip); mSocket = (); //3. After connecting, get the input stream and read client information InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; OutputStream os = null; is = (); isr = new InputStreamReader(is, "UTF-8"); br = new BufferedReader(isr); String info = null; while ((info = ()) != null) { ("Message sent by the client" + info); if ((BackService.HEART_BEAT_STRING)) { sendmsg("ok"); } else { sendmsg("Message sent by the server" + info); } } (); (); } catch (IOException e) { (); } } //Send information to each client on the server on the connection public static void sendmsg(String msg) { PrintWriter pout = null; try { pout = new PrintWriter(new BufferedWriter( new OutputStreamWriter((), "UTF-8")), true); (msg); } catch (IOException e) { (); } } }
2. For client writing, AIDL is mainly used for server and client
The writing of AIDL is mainly based on the following three parts:
1. Create AIDL
1) Create the entity class to operate and implement the Parcelable interface for serialization/deserialization
2) Create a new aidl folder, and create interface aidl file and mapping of entity class aidl file
3) Make project, generate Binder's Java file
2. Server side
1) Create a Service, create the Binder object instance generated above, and implement the interface definition method
2) Return in onBind()
3. Client
1) Implement the ServiceConnection interface and get the AIDL class in it
2)、bindService()
3) Call the operation request defined in the AIDL class
document
package ; // Declare any non-default types here with import statements interface IBackService { /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ boolean sendMessage(String message); }
The writing of Service, named BackService
public class BackService extends Service { private static final String TAG = "danxx"; public static final String HEART_BEAT_STRING = "HeartBeat";//Heartbeat package content /** * Heartbeat frequency */ private static final long HEART_BEAT_RATE = 3 * 1000; /** * Server IP address */ public static final String HOST = "172.16.50.115"; /** * Server port number */ public static final int PORT = 12345; /** * Server message reply broadcast */ public static final String MESSAGE_ACTION = "message_ACTION"; /** * Server heartbeat reply broadcast */ public static final String HEART_BEAT_ACTION = "heart_beat_ACTION"; /** * Read thread */ private ReadThread mReadThread; private LocalBroadcastManager mLocalBroadcastManager; /***/ private WeakReference<Socket> mSocket; // For heart Beat private Handler mHandler = new Handler(); /** * Heartbeat task, keep calling yourself repeatedly */ private Runnable heartBeatRunnable = new Runnable() { @Override public void run() { if (() - sendTime >= HEART_BEAT_RATE) { boolean isSuccess = sendMsg(HEART_BEAT_STRING);//Send a \r\nPast If the sending fails, reinitialize a socket if (!isSuccess) { (heartBeatRunnable); (); releaseLastSocket(mSocket); new InitSocketThread().start(); } } (this, HEART_BEAT_RATE); } }; private long sendTime = 0L; /** * aidl communication callback */ private iBackService = new () { /** * Received the message to send * @param message Message that needs to be sent to the server * @return * @throws RemoteException */ @Override public boolean sendMessage(String message) throws RemoteException { return sendMsg(message); } }; @Override public IBinder onBind(Intent arg0) { return iBackService; } @Override public void onCreate() { (); new InitSocketThread().start(); mLocalBroadcastManager = (this); } public boolean sendMsg(final String msg) { if (null == mSocket || null == ()) { return false; } final Socket soc = (); if (!() && !()) { new Thread(new Runnable() { @Override public void run() { try { OutputStream os = (); String message = msg + "\r\n"; (()); (); } catch (IOException e) { (); } } }).start(); sendTime = ();//Every time it is sent into data, change the last successful sending time to save the heartbeat interval } else { return false; } return true; } private void initSocket() {//Initialize Socket try { //1. Create a client Socket, specify the server address and port Socket so = new Socket(HOST, PORT); mSocket = new WeakReference<Socket>(so); mReadThread = new ReadThread(so); (); (heartBeatRunnable, HEART_BEAT_RATE);//After initialization is successful, you are ready to send a heartbeat packet } catch (UnknownHostException e) { (); } catch (IOException e) { (); } } /** * After the heartbeat mechanism determines that the socket has been disconnected, it will destroy the connection and facilitate recreating the connection. * * @param mSocket */ private void releaseLastSocket(WeakReference<Socket> mSocket) { try { if (null != mSocket) { Socket sk = (); if (!()) { (); } sk = null; mSocket = null; } } catch (IOException e) { (); } } class InitSocketThread extends Thread { @Override public void run() { (); initSocket(); } } // Thread to read content from Socket class ReadThread extends Thread { private WeakReference<Socket> mWeakSocket; private boolean isStart = true; public ReadThread(Socket socket) { mWeakSocket = new WeakReference<Socket>(socket); } public void release() { isStart = false; releaseLastSocket(mWeakSocket); } @Override public void run() { (); Socket socket = (); if (null != socket) { try { InputStream is = (); byte[] buffer = new byte[1024 * 4]; int length = 0; while (!() && !() && isStart && ((length = (buffer)) != -1)) { if (length > 0) { String message = new String((buffer, length)).trim(); (TAG, message); // When receiving a message from the server, it will be sent out via Broadcast if (("ok")) {//Processing heartbeat response Intent intent = new Intent(HEART_BEAT_ACTION); (intent); } else { //Reply to other messages Intent intent = new Intent(MESSAGE_ACTION); ("message", message); (intent); } } } } catch (IOException e) { (); } } } } @Override public void onDestroy() { (); (heartBeatRunnable); (); releaseLastSocket(mSocket); } }
MainActivity
public class MainActivity extends AppCompatActivity implements { private TextView mResultText; private EditText mEditText; private Intent mServiceIntent; private IBackService iBackService; private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { iBackService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { iBackService = (service); } }; class MessageBackReciver extends BroadcastReceiver { private WeakReference<TextView> textView; public MessageBackReciver(TextView tv) { textView = new WeakReference<TextView>(tv); } @Override public void onReceive(Context context, Intent intent) { String action = (); TextView tv = (); if ((BackService.HEART_BEAT_ACTION)) { if (null != tv) { ("danxx", "Get a heart heat"); ("Get a heart heat"); } } else { ("danxx", "Get a heart heat"); String message = ("message"); ("Server Message:" + message); } } } private MessageBackReciver mReciver; private IntentFilter mIntentFilter; private LocalBroadcastManager mLocalBroadcastManager; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main); mLocalBroadcastManager = (this); mResultText = (TextView) findViewById(.resule_text); mEditText = (EditText) findViewById(.content_edit); findViewById().setOnClickListener(this); findViewById(.send1).setOnClickListener(this); mReciver = new MessageBackReciver(mResultText); mServiceIntent = new Intent(this, ); mIntentFilter = new IntentFilter(); (BackService.HEART_BEAT_ACTION); (BackService.MESSAGE_ACTION); } @Override protected void onStart() { (); (mReciver, mIntentFilter); bindService(mServiceIntent, conn, BIND_AUTO_CREATE); } @Override protected void onStop() { (); unbindService(conn); (mReciver); } public void onClick(View view) { switch (()) { case : String content = ().toString(); try { boolean isSend = (content);//Send Content by socket (this, isSend ? "success" : "fail", Toast.LENGTH_SHORT).show(); (""); } catch (RemoteException e) { (); } break; case .send1: new Thread(new Runnable() { @Override public void run() { try { acceptServer(); } catch (IOException e) { (); } } }).start(); break; default: break; } } private void acceptServer() throws IOException { //1. Create a client Socket, specify the server address and port Socket socket = new Socket("172.16.50.115", 12345); //2. Obtain the output stream and send information to the server side OutputStream os = (); PrintWriter printWriter = new PrintWriter(os); //Package the output stream as a print stream //Get the IP address of the client InetAddress address = (); String ip = (); ("Client:~" + ip + "~ Access to the server!!"); (); (); (); } }
Source code address
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.