欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android编程实现简单的UDP Client实例

程序员文章站 2024-03-31 14:29:46
本文实例讲述了android编程实现简单的udp client。分享给大家供大家参考,具体如下: 该代码在4.2.2内调试通过 1.记得加权限

本文实例讲述了android编程实现简单的udp client。分享给大家供大家参考,具体如下:

该代码在4.2.2内调试通过

1.记得加权限

<uses-permission android:name="android.permission.internet"/>

注意:android 4.0之后,就不能在主线程进行socket通信,否则会抛异常。

2.代码

mainactivity.java:

package mao.example.quicksend;
import android.app.activity;
import android.content.context;
import android.os.bundle;
import android.os.handler;
import android.util.log;
import android.view.menu;
import android.view.menuitem;
import android.widget.button;
import android.widget.textview;
import android.widget.toast;
import android.view.view;
public class mainactivity extends activity {
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    initui();
    //获得button对象
    button btnconnect = (button) findviewbyid(r.id.buttonconnect);
    btnconnect.setonclicklistener(new button.onclicklistener() {
      public void onclick(view v)
      {
        //这里处理事件
        //connectserver();
        //udpclient udpet = new udpclient("192.168.0.14","123");
        //udpet.start();
        //displaytoast("点击了\"连接\"按钮");
      }
    });
    //发送button
    btnconnect = (button) findviewbyid(r.id.buttonsend);
    btnconnect.setonclicklistener(new button.onclicklistener() {
      public void onclick(view v)
      {
        //这里处理事件
        sendtext();
      }
    });
  }
  @override
  public boolean oncreateoptionsmenu(menu menu) {
    // inflate the menu; this adds items to the action bar if it is present.
    getmenuinflater().inflate(r.menu.main, menu);
    return true;
  }
  @override
  public boolean onoptionsitemselected(menuitem item) {
    // handle action bar item clicks here. the action bar will
    // automatically handle clicks on the home/up button, so long
    // as you specify a parent activity in androidmanifest.xml.
    int id = item.getitemid();
    if (id == r.id.action_settings) {
      return true;
    }
    return super.onoptionsitemselected(item);
  }
  /* 显示toast */
  public void displaytoast(string str)
  {
    toast.maketext(this, str, toast.length_short).show();
  }
  public void initui()
  {
    textview text=(textview)findviewbyid(r.id.edittextip);
    text.settext("192.168.0.14");
    text = (textview)findviewbyid(r.id.edittextfilepath);
    text.settext("udp client send test");
  }
  // connect server
  public void sendtext() 
  {
    textview editip=(textview)findviewbyid(r.id.edittextip);
    textview edittext=(textview)findviewbyid(r.id.edittextfilepath);
    string message = edittext.gettext().tostring() + "\r\n"; 
    udpclient udpet = new udpclient(editip.gettext().tostring(), message);
    udpet.start();
  }
}

udpclient.java:

package mao.example.quicksend;
import java.io.ioexception;
import java.net.datagrampacket;
import java.net.datagramsocket;
import java.net.inetaddress;
import java.net.socketexception;
import java.lang.string;
public class udpclient extends thread{
  public string m_serverip;
  public string m_text;
  public udpclient(string strserverip, string strtext)
  {
    m_serverip = strserverip;
    m_text = strtext;
  }
  @override
  public void run() {
    // todo auto-generated method stub
    int timeout = 3000;
    int servport = 8800;
    byte[] bytestosend = m_text.getbytes();//"test_client".getbytes();
    try {
      inetaddress serveraddress = inetaddress.getbyname(m_serverip);
      datagramsocket socket = new datagramsocket();
      socket.setsotimeout(timeout);
      datagrampacket sendpacket = new datagrampacket(bytestosend,bytestosend.length,serveraddress,servport);
      socket.send(sendpacket);
      socket.close();
    } catch (socketexception e){
      e.printstacktrace();
    }catch(ioexception e){
      e.printstacktrace();
    }
  }
}

3. activity_main.xml:

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/linearlayout1"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:paddingbottom="@dimen/activity_vertical_margin"
  android:paddingleft="@dimen/activity_horizontal_margin"
  android:paddingright="@dimen/activity_horizontal_margin"
  android:paddingtop="@dimen/activity_vertical_margin"
  tools:context="mao.example.quicksend.mainactivity" >
  <edittext
    android:id="@+id/edittextip"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/text_ip" />
  <button
    android:id="@+id/buttonconnect"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/text_connect" />
  <edittext
    android:id="@+id/edittextfilepath"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/text_filepath" >
    <requestfocus />
  </edittext>
  <button
    android:id="@+id/buttonfilesel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/text_sel" />
  <button
    android:id="@+id/buttonsend"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/text_send" />
</linearlayout>

更多关于android相关内容感兴趣的读者可查看本站专题:《android通信方式总结》、《android调试技巧与常见问题解决方法汇总》、《android开发入门与进阶教程》、《android多媒体操作技巧汇总(音频,视频,录音等)》、《android基本组件用法总结》、《android视图view技巧总结》、《android布局layout技巧总结》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。