package S.D;
/**
*
* by lili
* 2016-09-20
*
*/
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
public class AndUDPActivity extends Activity {
/** Called when the activity is first created. */
EditText et ;
TextView tv;
DatagramSocket ds;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et = (EditText) findViewById(R.id.et);
tv = (TextView) findViewById(R.id.tv);
et.setText("");
tv.setText("");
try {
//套接字
ds = new DatagramSocket();
new Thread(networkTask1).start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("发送");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==0){
new Thread(networkTask).start();
}
return super.onOptionsItemSelected(item);
}
/**
* 子线程 发送
*/
Runnable networkTask = new Runnable() {
@Override
public void run() {
/// ********************* 手机---> 电脑 *********************//
try {
//发送内容
String str = et.getText().toString();
//构建数据报(内容+地址)
DatagramPacket dp =
new DatagramPacket(str.getBytes(),
str.length(),
InetAddress.getByName("222.210.157.43"),
5050);
//把数据报发送出去
ds.send(dp);
//关闭套接字
//ds.close();
Message msg = new Message();
Bundle data = new Bundle();
data.putString("value", "手机已发送:" + str);
msg.setData(data);
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
};
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
String val = data.getString("value");
Log.i("LogTest", "结果为-->" + val);
tv.setText( tv.getText() + "\n" + val);
}
};
/**
* 接收数据
*/
Runnable networkTask1 = new Runnable() {
public void run() {
try {
/// ********************* 电脑---> 手机 *********************//
//2、创建数据包,用于接收内容。
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
while (true) {
ds.receive(packet);
//关闭套接字
//ds.close();
Message msg = new Message();
Bundle data = new Bundle();
data.putString("value", "手机接收到:" + new String(packet.getData(), 0, packet.getLength()));
msg.setData(data);
handler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}