`

【android】与pc机进行UDP通信

阅读更多
这里pc作为server接受小心并显示出来。
而android的作为客户端发送消息。

首先:服务端没有什么好说的。
直接上代码:
public class Server {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		DatagramSocket ds = new DatagramSocket(10000);
		while(true){
			byte [] b = new byte[1024];
			DatagramPacket dp = new DatagramPacket(b,b.length);
			ds.receive(dp);
			System.out.println("prot: "+dp.getPort());
			System.out.println("data: "+new String(dp.getData(),0,dp.getLength(),"utf-8"));
		}
	}

}


这里重点说android的客户端:
一说到网络技术别忘记在manifest.xml设定网络访问权限
<uses-permission android:name="android.permission.INTERNET" />  


其他的也不多说直接上代码吧
public class AndroidUdpActivity extends Activity {
    DatagramSocket ds = null;
    DatagramPacket dp = null;
    Button b = null;
    EditText et = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        b = (Button) this.findViewById(R.id.button1);
        et = (EditText) this.findViewById(R.id.editText1);

        try {
			ds = new DatagramSocket(54999);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		b.setOnClickListener(new OnClickListener() {
			// TODO Auto-generated method stub
			@Override
			public void onClick(View v) {     
//				String s = "welcome to c....";
				String s = et.getText().toString();
				
				byte [] buf = s.getBytes();
				int length = buf.length;
				
				try {
					dp = new DatagramPacket(buf,length,InetAddress.getByName("10.0.2.2"),10000);
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				try {
					System.out.println("port:" + ds.getLocalPort());
					ds.send(dp);
					et.setText("");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		
    }
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		ds.close();
		super.onStop();
	}
}


在layout/main.xml中就一个edittext和button。
这里重点就是虚拟机所在pc机的IP为10.0.2.2.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics