Android-Socket causes the Socket to close and cannot send and receive data after the IO stream is closed. androidio

Source: Internet
Author: User

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 !!!

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.