Android-Socket causes the Socket to close and cannot send and receive data after the IO stream is closed. androidio
Use Socket to send data as an example:
When sending data, declare: DataOutputStream OS = new DataOutputStream (socket. getOutputStream ());
Recently, I encountered the question: I want to send images to the server. If OS. close () is used, the server will receive the images, but the socket of my client will be affected and closed. If you do not need OS. close (), the server will have an impact on the image reception. You can call socket. shutdownOutputStream () to check the information, and disable the output stream without affecting the data sending by the socket.
But the problem arises: DataOutputStream is disabled, but the client still needs to send data. How can I enable DataOutputStream?
I don't have a proper answer from Baidu, so when I send data again, I first determine whether the output stream is closed. If it is closed, I will create another Soket .... (I personally think this method does not solve the current problem, but it is not the best. If you have a better solution, please leave a message. Thank you very much !!!!)
Public void sendObject (String obj) throws IOException {// determine whether the output stream is closed. If yes, restart new Socketif (socket. isOutputShutdown () {socket = new Socket (SERVERIP, PORT);} DataOutputStream OS = new DataOutputStream (socket. getOutputStream (); // OS. write (obj. getBytes (); OS. writeUTF (obj); OS. flush (); System. out. println ("client sends" + obj + "to server ");}
If you have a good method, thank you for leaving a message !!!