Application analysis of socket in Android

This paper analyzes the application of socket in Android. Share with you for your reference, as follows:

Common network programming provided by Android includes socket communication for TCP / IP protocol. Socket is a cross platform programming method, which can communicate between heterogeneous languages.

The development principle of socket program is to realize server-side and client-side.

The server uses ServerSocket to listen to the specified port. The port can be specified at will (since ports below 1024 are usually reserved ports and can not be used at will in some operating systems, it is recommended to use ports greater than 1024). Wait for the customer's connection request. After the customer connects, the session will be generated; After completing the session, close the connection.

The client uses the socket to send a connection request to a port of a server on the network. Once the connection is successful, open the session; After the session is completed, close the socket. The client does not need to specify the open port, and usually temporarily and dynamically allocate more than 1024 ports.

The following is an example of socket implementation:

Server side code:

Customer service code:

XML file layout:

Start the server first, and then run the client program.

be careful:

(1) Even if the server and client are running on the same machine, the IP address: 127.0.0 cannot be used 0.1, otherwise, the program will reject the connection.

(2) It is better not to build the client and server under the same project. It is better to build the project separately, and then start the server and client, otherwise an error: shouldnotrachhere() error will be reported. This is because the Android program is not an entry that has the main method as the program.

Operation effect:

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
分享
二维码
< <上一篇
下一篇>>