Android 开发:多线程编程(2)

线程类socke_sendt.java:

package test.soket;      import java.io.DataOutputStream;     import java.io.IOException;     import java.net.DatagramPacket;   import java.net.DatagramSocket;   import java.net.InetAddress;   import java.net.Socket;     import java.net.SocketException;   import java.net.UnknownHostException;     import java.util.LinkedList;          import android.media.AudioFormat;     import android.media.AudioRecord;     import android.media.MediaRecorder;     import android.util.Log;         public class soket_send extends Thread   {        private static final int MAX_DATA_PACKET_LENGTH = 40;       private byte[] buffer = new byte[MAX_DATA_PACKET_LENGTH];       private DatagramPacket dataPacket;       private DatagramSocket udpSocket;               public void init()         {             try           {               udpSocket = new DatagramSocket(5554);           }           catch (SocketException e)           {               // TODO Auto-generated catch block                e.printStackTrace();           }           dataPacket = new DatagramPacket(buffer, MAX_DATA_PACKET_LENGTH);           String str = "hello,jdh";  //这是要传输的数据            byte out [] = str.getBytes();  //把传输内容分解成字节            dataPacket.setData(out);           dataPacket.setLength(out.length);           dataPacket.setPort(5554);                      try           {                                  InetAddress broadcastAddr = InetAddress.getByName("192.168.0.248");               dataPacket.setAddress(broadcastAddr);               udpSocket.send(dataPacket);           }           catch (IOException e)           {               // TODO Auto-generated catch block                e.printStackTrace();           }            }                public void run()        {             while (true)           {               if (test_socket.flag)               {                   //获得输入框文本                    CharSequence str =test_socket.show.getText();                   byte out[] = str.toString().getBytes();                   dataPacket.setData(out);                   dataPacket.setLength(out.length);                   try                   {                                                  InetAddress broadcastAddr = InetAddress.getByName("192.168.0.248");                       dataPacket.setAddress(broadcastAddr);                       udpSocket.send(dataPacket);                   }                   catch (IOException e)                   {                       // TODO Auto-generated catch block                        e.printStackTrace();                   }                                      test_socket.flag = false;               }           }       }     }  

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwdjjz.html