Android socket programming

Source: Internet
Author: User

The first step is to use the local computer to communicate with the android simulator on the local computer. The reason is that the main UI thread of Android cannot execute a working thread, that is, to execute network operations.
There are two solutions:
1 \ reference http://android.yyable.com/reference/android/ OS /StrictMode.html

2 \ Delete <uses-SDK Android: minsdkversion = "14"/> In androidmanifest. xml

You can also use other methods, such as handler.

At first, we thought it was a permission issue.

The android simulator receives UDP data packets from the PC as a server,
Port ing needs to be performed on the simulator. The commands used are somewhat different from those used in TCP.
Redir add UDP: 8000: 9000
After this is done, you can receive the UDP package!

There are two ways to create a thread: Inherit the Thread class and implement the runnable interface. Method 1: Inherit the Thread class and overwrite the run () method. In the subclass of the created Thread class, rewrite run () and add the code to be executed by the thread. The following is an example:
Public class mythread extends thread {int COUNT = 1, number; Public mythread (INT num) {number = num; system. out. println ("create thread" + number);} public void run () {While (true) {system. out. println ("Thread" + number + ": Count" + count); If (+ + Count = 6) return ;}} public static void main (string ARGs []) {for (INT I = 0; I <5; I ++) New mythread (I + 1 ). start ();}}

Method 2: there is only one method to implement the runnable interface runnable (). We declare our class to implement the runnable interface and provide this method to write our thread code into it, this part of the task is completed. However, the runnable interface does not support any threads. We must also create an instance of the thread class, which is achieved through the Thread class constructor public thread (runnable target. The following is an example:

Public class mythread implements runnable {int COUNT = 1, number; Public mythread (INT num) {number = num; system. out. println ("create thread" + number);} public void run () {While (true) {system. out. println ("Thread" + number + ": Count" + count); If (+ + Count = 6) return ;}} public static void main (string ARGs []) {for (INT I = 0; I <5; I ++) New thread (New mythread (I + 1 )). start ();}}

Runnable is just a callback interface. Not all runnable is used for threads. If it is used as a thread, it is passed to the Thread class to the executor class.

As long as it is about the UI, it cannot be placed in the sub-thread, because the sub-thread cannot operate the UI, and can only perform data, system, and other non-UI operations.

1. Put the things passed by the handle object in a message loop queue. If there is no such message loop queue, an error will be reported!

2. during simple thread communication, we only use handler in the main activity thread. the sendmessage (Message) method is used to send messages, and handler is used. the handlemessage (Message) class can be used to obtain messages. This does not seem to have any errors, and it does not seem to have any errors if we send messages to the main activity thread in a common thread that we have enabled, you can capture the desired message.

3. But if the thread for receiving messages is not the main thread but a common thread, an error will be reported. Why? This is because there is no message loop queue in our custom common thread. So how can we implement a message loop queue? (Suppose we have all rewritten the handlemessage (Message) method)

(1) This is the simplest method. It is to pass in the looper object obtained by calling handlerthread. getlooper () when instantiating the handler object. This Looper object is the message loop queue we need. Of course, this handlerthread object must call the START () method to run the thread enabled by him.

(2) This method is written by imitating the run () method of the handlerthread class. The logoff. Prepare () method is added before the handler object is defined to let the message loop start preparation. After the definition is complete, the logoff. Loop () method is called. However, the message loop starts to run. In fact, there is no difference between the two methods. They all add a message queue to a common thread.

4. Why is there no problem in the activity?

The reason is that activity is actually nothing. It's just a big monster. He integrates many functions and encapsulates them, of course, there is also a message loop Queue (this message loop queue is maintained by the system), so there is no error in passing messages with handler in a simple main activity. Some people say that the activity is actually not like this. We only see a window or view. He uses the window function to listen to events and display the interface with the view function, it also integrates data storage and other functions.

Communication code:

UDP Communication implementation: UDP uses the datagramsocket object to Implement UDP client code implementation as follows: public static void main (string [] ARGs) {try {// first create a initramsocket object initramsocket socket = new initramsocket (4567); // create an inetaddreetaddress serveraddress = inetaddress. getbyname ("192.168.1.104"); string STR = "hello"; // This is the data to be transmitted byte data [] = Str. getbytes (); // splits the transmitted content into bytes. // creates a datagrampacket object and specifies the address and port number of the packet sent to the network. Cket = new datagrampacket (data, data. length, serveraddress, 4567); // call the send method of the socket object to send data socket. send (packet);} catch (exception e) {// todo auto-generated Catch Block E. printstacktrace () ;}} the UDP server code is implemented as follows: // create a initramsocket object and specify the listening port number as follows ); byte data [] = new byte [1024]; // create an empty mongorampacket object mongorampacket packet = new mongorampacket (data, data. l Ength); // use the receive method to receive data sent by the client. // if the client does not send data, the process will be stuck in the socket. receive (packet); string result = new string (packet. getdata (), packet. getoffset (), packet. getlength (); system. out. println ("result --->" + result); 5. TCP communication implementation: TCP uses the socket object tcp client implementation: // create a socket object, specify the IP address and port number of the server Socket socket = new socket ("192.168.1.104", 4567); // use inputstream to read files on the hard disk inputstream = new fileinputstream ("F: // File/words.txt "); // obtain outputstream = socket from the socket. getoutputstream (); byte buffer [] = new byte [4*1024]; int temp = 0; // extracts data from inputstream, and write it to outputstream while (temp = inputstream. read (buffer ))! =-1) {outputstream. write (buffer, 0, temp);} outputstream. flush ();} TCP protocol server reality: // declare a serversocket object serversocket = NULL; try {// create a serversocket object, and let the socket listen to serversocket = new serversocket (4567) on port 4567; // call the serversocket accept () method to accept the request sent by the client, // if the client does not send data, the thread will be stuck and the Socket socket = serversocket will not continue. accept (); // obtain the inputstream object inputstream = socket from the socket. getinputstre Am (); byte buffer [] = new byte [1024*4]; int temp = 0; // read the data sent by the client from inputstream while (temp = inputstream. read (buffer ))! =-1) {system. out. println (new string (buffer, 0, temp) ;}} catch (ioexception e) {// todo auto-generated Catch Block E. printstacktrace ();} serversocket. close ();}

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.