基於UDP協議的小車控制android軟件

測試的時候分爲服務器端和客戶端;

先看效果:

客戶端

 

服務器:

客戶端是android軟件,源碼如下:

/**
 * @author jiefu
 * 小車控制系統
 */

package com.pansino.car;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import roman10.tutorial.udpcommclient.R;

import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class CarControlActivity extends Activity implements OnClickListener{
	/** Called when the activity is first created. */
	private static final int UDP_SERVER_PORT = 11111;
	private Button btn_forword,btn_back,btn_left,btn_right;
	private TextView tv_show;//控制檯
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);
		findViews();
		registerListener();
	}

	/**
	 * 查找控件
	 */
	private void findViews(){
		btn_forword = (Button) findViewById(R.id.btn_forword);
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_left = (Button) findViewById(R.id.btn_left);
		btn_right = (Button) findViewById(R.id.btn_right);
		tv_show = (TextView) findViewById(R.id.tv_show);
		tv_show.setMovementMethod(ScrollingMovementMethod.getInstance());
		tv_show.append("\n");
	}
	
	/**
	 * 註冊監聽
	 */
	private void registerListener(){
		btn_forword.setOnClickListener(this);
		btn_back.setOnClickListener(this);
		btn_left.setOnClickListener(this);
		btn_right.setOnClickListener(this);
	}
	
	/**
	 * UDP客戶端
	 * @param string
	 */
	private void runUdpClient(String string) {
		String udpMsg = string;
		DatagramSocket ds = null;
		try {
			ds = new DatagramSocket();
			InetAddress serverAddr = InetAddress.getByName("192.168.111.62");
			DatagramPacket dp;
			dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(),
					serverAddr, UDP_SERVER_PORT);
			ds.send(dp);	
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ds != null) {
				ds.close();
			}
		}
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.btn_forword:
			runUdpClient("forword");
			tv_show.append("send:小車前進"+"\n");
			break;
		case R.id.btn_back:
			runUdpClient("back");
			tv_show.append("send:小車後退"+"\n");
			break;
		case R.id.btn_left:
			runUdpClient("left");
			tv_show.append("send:小車左轉"+"\n");
			break;
		case R.id.btn_right:
			runUdpClient("right");
			tv_show.append("send:小車右轉"+"\n");
			break;
		default:
			break;
		}
	}
}
別忘記加入權限:<uses-permission android:name="android.permission.INTERNET"/>


服務器端接受數據,放在PC機上,源碼如下:
package inetaddressdemo;

// DGSServer.java

import java.io.*;
import java.net.*;

class DGSServer
{
   public static void main (String [] args) throws IOException  {
      System.out.println ("Server starting ...\n");
      // Create a datagram socket bound to port 10000. Datagram
      // packets sent from client programs arrive at this port.
      //DatagramSocket s = new DatagramSocket (10000);
      DatagramSocket s = new DatagramSocket (11111);
      // Create a byte array to hold data contents of datagram
      // packet.
      byte [] data = new byte [100];
      // Create a DatagramPacket object that encapsulates a reference
      // to the byte array and destination address information. The
      // DatagramPacket object is not initialized to an address
      // because it obtains that address from the client program.
      DatagramPacket dgp = new DatagramPacket (data, data.length);
      // Enter an infinite loop. Press Ctrl+C to terminate program.
      while (true){
      // Receive a datagram packet from the client program.
        s.receive (dgp);
        String result = new String(data, 0, dgp.getLength());
        // Display contents of datagram packet.
        System.out.println (result);
        // Echo datagram packet back to client program.
        //s.send (dgp);
      }
   }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章