先贴代码: 请耐心看看,有点多,但是简单,谢谢
- Java code
package xiaobenben.muticast;import java.io.IOException;import java.net.DatagramPacket;import java.net.InetAddress;import java.net.MulticastSocket;import java.util.Scanner;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;public class Muticast extends Activity { /** Called when the activity is first created. */ private Button button_ok; private TextView textview; private Button button_begin; private EditText edittext; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button_ok = (Button)findViewById(R.id.button_ok); button_begin = (Button)findViewById(R.id.button_begin); textview = (TextView)findViewById(R.id.textview_text); edittext = (EditText)findViewById(R.id.editview); textview.setText("hi,xiaobenben!"); button_begin.setOnClickListener(new Button.OnClickListener(){ public void onClick(View v) { // TODO Auto-generated method stub try { System.out.println("init() start"); new Multicast().init(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } class Multicast implements Runnable{ private static final String BROADCAST_IP = "230.0.0.1"; public static final int BROADCAST_PORT = 30000; private static final int DATA_LEN = 4096; private MulticastSocket socket = null; private InetAddress broadcastAddress = null; private Scanner scan = null; byte[] inBuff = new byte[DATA_LEN]; private DatagramPacket inPacket = new DatagramPacket(inBuff , inBuff.length); private DatagramPacket outPacket = null; private String str; public void init()throws IOException { try { socket = new MulticastSocket(BROADCAST_PORT); broadcastAddress = InetAddress.getByName(BROADCAST_IP); socket.joinGroup(broadcastAddress); socket.setLoopbackMode(false); outPacket = new DatagramPacket(new byte[0] , 0 ,broadcastAddress , BROADCAST_PORT); new Thread(this).start(); scan = new Scanner(edittext.getText().toString()); while(scan.hasNextLine()) { byte[] buff = scan.nextLine().getBytes(); outPacket.setData(buff); socket.send(outPacket); } } finally { socket.close(); } } public void run(){ try { while(true) { socket.receive(inPacket); System.out.println("聊天信息:" + new String(inBuff , 0 , inPacket.getLength())); textview.setText("聊天信息:" + new String(inBuff , 0 , inPacket.getLength())); System.out.println(inPacket.getAddress().getHostAddress()); } } catch (IOException ex) { ex.printStackTrace(); try { if (socket != null) { socket.leaveGroup(broadcastAddress); socket.close(); } System.exit(1); } catch (IOException e) { e.printStackTrace(); } } } }}