Android Network Programming Socket (1)

Source: Internet
Author: User

In Android Network Communication, sockets are usually used for data communication between the number of devices and Http is used for network data requests.
1. Socket)
Anyone with Java development experience or. NET development experience should have a more or less understanding of Socket. Common TCP or UDP protocols are actually implemented based on Socket.
A Socket is used to describe a process or application in a device on the network. A Socket consists of an IP address and a port number. IP addresses are used to locate devices and port numbers are used to locate applications or processes, such as common HTTP protocols running on port 80. The common format of Socket is 192.168.1.1: 1234.
How does an application communicate with other devices on the network through a Socket? Generally, the Socket communication includes two parts: the listening Server and the actively requesting Client. The Server listens to the port in the Socket until there is a request. When the Client sends a connection request to the port, the Server responds and returns a Socket object, in the future, you can use this Socket for data exchange between the Server and the Client.
2. Use Socket for data exchange in Android
ServerSocket
Server), you need to use the ServerSocket object, this object will automatically listen to the port number passed in its constructor, and after receiving the connection request, use ServerSocket. the accept () method returns a connected Socket object. This method does not need to use the Start method as in. NET. It will automatically listen.
Socket
Whether you create a Client or perform other data exchange operations, you must use the Socket class. During initialization, the Socket class needs to access the IP address and port number of the Server and return a Socket object connected to the Server. If the connection fails, an exception is returned. Same as ServerSocket, it also automatically makes connection requests.
After the above two steps, the Server and Client can be connected, but only the connection is useless. Data Exchange is our purpose, in this case, the OutputStream class and InputStream class in the IO stream are used.
OutputStream-- Writable stream
When the application needs to write data to the stream, you can use the data stream returned by the Socket. getOutputStream () method.
InputStream-- Readable stream
To retrieve data from a stream, you can use the data stream returned by Socket. getInputStream () to perform operations.
Let's take a look at the complete code.

 
 
  1. View Code
  2. Package LiB. Demo;
  3. Import java. io. BufferedReader;
  4. Import java. io. BufferedWriter;
  5. Import java. io. IOException;
  6. Import java. io. InputStreamReader;
  7. Import java. io. OutputStreamWriter;
  8. Import java.net. ServerSocket;
  9. Import java.net. Socket;
  10. Public class SocketHelper {
  11. Private static ServerSocket serverSocket = null;
  12. Private static Socket client = null;
  13. Private final static int port = 9048;
  14. Private static BufferedReader br = null;
  15. Private static BufferedWriter bw = null;
  16. /**
  17. * Create a SocketServer object to create a server
  18. * @ Throws IOException
  19. */
  20. Public static void CreateServer () throws IOException
  21. {
  22. ServerSocket = new ServerSocket (port, 10 );
  23. System. out. println ("start listening ...");
  24. }
  25. /**
  26. * Create a Socket object to connect to the SocketServer object
  27. * @ Param dstName the IP address of the Server Object
  28. * @ Return
  29. * @ Throws IOException
  30. */
  31. Public static Socket CreateClient (String dstName) throws IOException
  32. {
  33. Socket socket = new Socket (dstName, port );
  34. // Socket sockets = new Socket ("192.168.8.12", port );
  35. Return socket;
  36. }
  37. /**
  38. * Returns a Socket object that has been connected to the server.
  39. * @ Throws IOException
  40. */
  41. Public static void GetClinetSocket () throws IOException
  42. {
  43. Client = serverSocket. accept ();
  44. System. out. println ("get a connected client ");
  45. }
  46. /**
  47. * Send data to the Stream Obtained by the socket object
  48. * @ Param socket
  49. * @ Param msg
  50. * @ Throws IOException
  51. */
  52. Public static void SendMsg (Socket socket, String msg) throws IOException
  53. {
  54. Bw = new BufferedWriter (new OutputStreamWriter (socket. getOutputStream ()));
  55. Bw. write (msg );
  56. Bw. flush ();
  57. Bw. close ();
  58. }
  59. /**
  60. * Obtain data in the socket object stream
  61. * @ Param socket
  62. * @ Param msg
  63. * @ Return
  64. * @ Throws IOException
  65. */
  66. Public static String ReceiveMsg (Socket socket, String msg) throws IOException
  67. {
  68. Br = new BufferedReader (new InputStreamReader (socket. getInputStream ()));
  69. String receiveMsg = "Receive msg:" + br. readLine ();
  70. Br. close ();
  71. Return receiveMsg;
  72. }
  73. /**
  74. * Release the socket object
  75. * @ Throws IOException
  76. */
  77. Public static void Close () throws IOException
  78. {
  79. If (client! = Null)
  80. {
  81. Client. close ();
  82. }
  83. If (serverSocket! = Null)
  84. {
  85. ServerSocket. close ();
  86. }
  87. }
  88. }

Next page will introduce youHTTP CommunicationContent


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.