Android uses socket to create simple TCP connection

This article gives an example of how Android uses socket to create a simple TCP connection. Share with you for your reference, as follows:

Communication is an important part of both Java and Android programming. There is no doubt about the importance of connected socket programming.

Here is a simple demo to demonstrate the most basic socket programming.

Write the server first. The server is java code. I don't bother to install eclipse and other programming software. I just program directly with notepad and run with DOS. The server usually creates a new server socket bound to the port to listen to client requests (dead loop listening). When a client message is received, the message is read, processed, and then returned to the client. The code is as follows: (more detailed comments have been made)

The client creates a new socket with bound IP (server) and port number (the same as the server), then sends the content to the server in the form of stream (pay attention to giving the end flag here, such as semi closed), and reads the returned content (reading here is a waiting process, that is, if the server sends back a message for a long time, it will read, and if it does not send back, it will wait, that is, blocking). Finally, close the socket. The code is as follows:

Finally, after running the server, you can run the client for demonstration.

For more Android related content, readers who are interested can view the topics on this site: summary of Android communication methods, summary of Android debugging skills and solutions to common problems, introduction and advanced tutorial of Android development, summary of Android multimedia operation skills (audio, video, recording, etc.), summary of the usage of Android basic components Summary of Android view skills, summary of Android layout skills and summary of Android control usage

I hope this article will help you in Android programming.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>