android两台真机的sock udp 通信

http://download.csdn.net/detail/zyp009/4885734实现两台手机(真机android系统)之间的通信,采用wifi无线路由器的模式

其中接收方的代码A  MainActivity .java:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	private TextView SendT;
	private String TAG="A";
	private String test="";
	private RemoteThread mRemoteThread=null;
	private Button mButton,mButtongx;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        SendT= (TextView) findViewById(R.id.Text);
        mButtongx= (Button) findViewById(R.id.buttgx);
//	模拟器   
        if(mRemoteThread == null) {
			mRemoteThread = new RemoteThread();
			mRemoteThread.start();
			Log.i(TAG, "start");
		}
        mButtongx.setOnClickListener(new OnClickListener() {
        	
        	@Override
        	public void onClick(View v) {
        		Log.v(TAG, test);
        		if(!test.equals("")){
        			SendT.setText("收到信息"+test);
        			test="";
        			mButtongx.setText("清空");
        		}
        		else {
        			SendT.setText("null"+test);
        			mButtongx.setText("更新");
        		}
        	}
        });
	}

    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		mRemoteThread.exit();
		test="";
	}


	private class RemoteThread extends Thread {
		private boolean mKeepRunning = true;	
		
		public void exit() {
			mKeepRunning = false;
		}
		
		@Override
    	public void run() {
			DatagramSocket socket = null;
	        byte[] data = new byte[1024];
	        int port = 7001;
	        DatagramPacket packet = new DatagramPacket(data, data.length);
	        
	        try {
	        	Log.i(TAG, "ip ");
	        	socket = new DatagramSocket(port);
	        	Log.i(TAG, "socket");
//	        	socket.setSoTimeout(200);
	        } catch(Exception e) {
	        	e.printStackTrace();
	        	return;
	        }
            
	        while (mKeepRunning) {            
                try {
                	//等待客户机连接
                	packet.setData(data);
                	Log.i(TAG, "receive0");
                	socket.receive(packet);
                	test=new String(packet.getData(), 0, packet.getLength());
                	Log.i(TAG,"receive1"+test);
                	
//                	InetAddress addr = packet.getAddress();
//                	if (addr.getHostAddress().equals("10.0.2.2"))
//                		packet.setAddress(InetAddress.getByName("192.168.1.110"));
                } catch (Exception e) {
                	continue;
                }
	        }
	        
	        if (socket != null) {
	        	socket.close();
	        	socket = null;
	        }
	    }
    }
}

发送方的代码B  MainActivity .java:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	//真机
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
		try {
			DatagramSocket sendSocket = new DatagramSocket();
			
			String mes = "BB:B is not A";
			byte[] buf = mes.getBytes();
			
			
			int port = 7001;	// 确定发送方的IP地址及端口号
			InetAddress ip = InetAddress.getByName("192.168.1.100");		//即A的手机Ip号	
			DatagramPacket sendPacket = new DatagramPacket(buf, buf.length, ip,port);// 创建发送类型的数据报:

			sendSocket.send(sendPacket);	// 通过套接字发送数据:			
			System.out.println("发送消息  :" + mes);
			
			sendSocket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}

B的activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="I am B"
        tools:context=".MainActivity" />

   

    <Button
        android:id="@+id/buttongx"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button1"
        android:layout_alignLeft="@+id/button1"
        android:text="更新" />

</RelativeLayout>

重点:A、B两个工程的AndroidManifest.xml都要加上<uses-permission android:name="android.permission.INTERNET">  </uses-permission>。


先运行A的 MainActivity .java工程,再运行B的 MainActivity .java工程

点击A是更新按钮。可看到A的效果如下



总结:一直调不通主要是因为接收方没有使用线程Thread ,所以不行。加了线程就OK了大笑

源码:http://download.csdn.net/detail/zyp009/4885734


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值