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

所属分类: 软件编程 / Android 阅读数: 1496
收藏 0 赞 0 分享

本文实例讲述了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程序设计有所帮助。

更多精彩内容其他人还在看

Android网络编程之获取网络上的Json数据实例

这篇文章主要介绍了Android网络编程之获取网络上的Json数据实例,本文用完整的代码实例讲解了在Android中读取网络中Json数据的方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Android中的windowSoftInputMode属性详解

这篇文章主要介绍了Android中的windowSoftInputMode属性详解,本文对windowSoftInputMode的9个属性做了详细总结,需要的朋友可以参考下
收藏 0 赞 0 分享

Android网络编程之UDP通信模型实例

这篇文章主要介绍了Android网络编程之UDP通信模型实例,本文给出了服务端代码和客户端代码,需要的朋友可以参考下
收藏 0 赞 0 分享

Android中使用ListView实现漂亮的表格效果

这篇文章主要介绍了Android中使用ListView实现漂亮的表格效果,本文用详细的代码实例创建了一个股票行情表格,需要的朋友可以参考下
收藏 0 赞 0 分享

Android中刷新界面的二种方法

这篇文章主要介绍了Android中刷新界面的二种方法,本文使用Handler、postInvalidate两种方法实现界面刷新,需要的朋友可以参考下
收藏 0 赞 0 分享

Android SDK三种更新失败及其解决方法

这篇文章主要介绍了Android SDK三种更新失败及其解决方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Android学习笔记——Menu介绍(一)

Android3.0(API level 11)开始,Android设备不再需要专门的菜单键。随着这种变化,Android app应该取消对传统6项菜单的依赖。取而代之的是提供anction bar来提供基本的用户功能
收藏 0 赞 0 分享

Android学习笔记——Menu介绍(二)

这次将继续上一篇文章没有讲完的Menu的学习,上下文菜单(Context menu)和弹出菜单(Popup menu)
收藏 0 赞 0 分享

Android学习笔记——Menu介绍(三)

今天继续昨天没有讲完的Menu的学习,主要是Popup Menu的学习,需要的朋友可以参考下
收藏 0 赞 0 分享

Android显示网络图片实例

这篇文章主要介绍了Android显示网络图片的方法,以实例形式展示了Android程序显示网络图片的方法,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多