Socket programming for Android Development

Source: Internet
Author: User

I. Socket Introduction

1.The so-called Socket is also known as "Socket", used to describe the IP address and port, is a communication chain handle
2.Applications usually send requests to or respond to network requests through sockets
3.The Socket has two main operation methods: connection-oriented TCP) and connectionless UDP ).
4.Java.net provides two types of Socket and ServerSocket, which are used to represent the client and server connected in two-way.
To initiate a communication, a client must first know the Host IP address of the running server. Then, the network infrastructure uses the target address to transmit the information sent by the client to the correct host. in Java, the address can be defined by a character or string, this string can be a numeric address such as 192.168.1.1) or a host name such as example.com ). In Java, the InetAddress class represents a network destination address, including host name and digital address information.

2. Use a TCP-based Socket

1. ServerSocket:
ServerSocket: This class implements a server-side Socket, which can be used to listen to requests from the network.
(A) method for creating ServerSocket:
ServerSocket (IntlocalPort)
ServerSocket (int localport, intqueueLimit)
ServerSocket (int localport, intqueueLimit, InetAddress localAddr)
To create a ServerSocket, you must specify a port so that the client can send a connection request to the port. The valid port range is 0-65535 (0-1023 is reserved by the system, preferably over 1024)
0 ~ The port number of 1023 is reserved by the system. For example, the port number of the http service is 80, the port number of the telnet service is 21, and the ftp is 23. Therefore, when selecting a port number, we 'd better select a number greater than 1023 to prevent conflict. When a Socket is created, if an error occurs, an IOException is generated and must be processed in the program. Therefore, you must capture or throw an exception when creating a Socket or ServerSocket.
(B) ServerSocket operations
1)Socketaccept ()
The accept () method creates a Socket instance for the next incoming connection request and returns the successfully connected Socket instance to the server Socket. If there is no connection request, the accept () method will block the wait;
2)Void close
The close method is used to close the socket.

2. Socket
(A) method for creating a Socket:
SocketInetAddress remoteAddress, intremotePort)
Using the Socket constructor, you can create a TCP Socket and connect to the specified remote address and port number first.
SocketInetAddress address, int port, InetAddress localAddr, intlocalPort)
Socket (InetAddress address, int port, booleanstream)
SocketSocketImpl impl)
Address, host, and port respectively indicate the IP address, host name, and port number of the other side of the two-way connection.
Stream indicates whether the Socket is a stream Socket or a datagram Socket.
LocalAddr, bindAddr is the address of the Local Machine ServerSocket host address)
Impl is the parent class of Socket. It can be used to create both ServerSocket and Socket.
(B) Socket operation method
Order in communication: the server first obtains the input stream, and then outputs the input stream information to each of its clients.
Socket provides the getInputStream () and getOutputStream () methods to obtain the input and output streams. Then read and write the output stream of the input stream. For example, after obtaining the Socket object on the server side, call the getInputStream method to obtain the stream from the client, call the getOutStream method to obtain the stream that sends data to the client. For the client, call the getInputStream method to obtain the stream from the server. Call the getOutStream method to obtain the stream that sends data to the server.
InputStreamgetInputStream ()
OutputStreamgetOutputStream ()
You can call the close () method of the Socket to close the function. Before closing the function, close all input and output streams related to the Socket.

3. programming steps:
To create a server:
The specified port instantiates a ServerSocket and calls the ServerSocket accept method to obtain the stream that is located in the underlying Socket during the connection waiting for blocking. The read and write operations encapsulate the data into a stream that reads and writes the Socket.
To create a client:
Instantiate a Socket through an IP address and port, and request the connection server to obtain the stream on the Socket for reading and writing. Pack the stream into the BufferedReader/PrintWriter instance to read and write the Socket.

To monitor multiple clients, you can use the class ExecutorService
Method for obtaining the object: Executors. newCachedThreadPool ();
Call the execute (Runnablecommand) of this object to execute the given command at a certain time in the future. This command may be executed in a new thread, a thread in the pool, or a calling thread, which is determined by the Executor implementation.

3. Use UDP-based Socket

A) create a DatagramSocket.
DatagramSocket (byte [] data, effecffset, int length, InetAddress remoteAddr, intremotePort)
This constructor creates a data packet object. The data is contained in the first parameter data.
Offset refers to the Offset length, and length refers to the data packet length.
B) Create a DatagramSocket.
DatagramSocket (intlocalPort)
The preceding constructor creates a UDP socket;
C) sending and receiving ramsocket
Void send (DatagramPacketpacket)
Void receive (DatagramPacketpacket)
The send () method is used to send the DatagramPacket instance. Once a connection is created, the datagram is sent to the connected address of the socket;
The receive () method blocks the wait, knows the received data packet, and copies the data in the packet to the specified DatagramPacket instance.

Supplement:

Do not forget to configure AndroidManifest. xml:
<Uses-permissionandroid: name = "android. permission. INTERNET"/>

The input and output streams must use DataOutputStream and DataOutputStream. PrintWriter and StreamReader cannot be used.

Edit recommendations]

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.