本文实例讲述了android开发socket编程之udp发送实现方法。分享给大家供大家参考。具体分析如下:
需要实现的功能:采用udp下的socket编程,当按下确认键,模拟器发送文本框数据,pc机上的网络调试助手接收
一、环境:
win7 + eclipse + sdk
二、代码:
package test.soket;
//import com.test_button.R;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class test_socket extends Activity {
public static TextView show;
public static Button press;
public static boolean flag;
private static final int MAX_DATA_PACKET_LENGTH = 40;
private byte[] buffer = new byte[MAX_DATA_PACKET_LENGTH];
private DatagramPacket dataPacket;
private DatagramSocket udpSocket;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//开辟控件空间
show = (TextView)findViewById(R.id.editText1);
press = (Button)findViewById(R.id.button1);
flag = false;
//soket_send thread = new soket_send();
//thread.init();
//thread.start();
try
{
udpSocket = new DatagramSocket(5554);
}
catch (SocketException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
dataPacket = new DatagramPacket(buffer, MAX_DATA_PACKET_LENGTH);
String str = "hello,jdh"; //这是要传输的数据
byte out [] = str.getBytes(); //把传输内容分解成字节
dataPacket.setData(out);
dataPacket.setLength(out.length);
dataPacket.setPort(5554);
try
{
InetAddress broadcastAddr = InetAddress.getByName("192.168.0.248");
dataPacket.setAddress(broadcastAddr);
udpSocket.send(dataPacket);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
press.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v)
{
flag = true;
//获得输入框文本
CharSequence str =test_socket.show.getText();
byte out[] = str.toString().getBytes();
dataPacket.setData(out);
dataPacket.setLength(out.length);
try
{
InetAddress broadcastAddr = InetAddress.getByName("192.168.0.248");
dataPacket.setAddress(broadcastAddr);
udpSocket.send(dataPacket);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
界面如下:
注意:在模拟器IP为本机IP,端口为模拟器名称
希望本文所述对大家的Android程序设计有所帮助。
您可能感兴趣的文章:Android Socket通信详解Android编程之客户端通过socket与服务器通信的方法Android中Socket通信的实现方法概述python服务器与android客户端socket通信实例Android中使用socket通信实现消息推送的方法详解Android开发中Socket通信的基本实现方法讲解android Socket实现简单聊天功能以及文件传输详解Android使用Socket对大文件进行加密传输Android开发之Socket通信传输简单示例