天行健,君子以自强不息
分类: Android平台
2015-09-01 19:12:31
点击(此处)折叠或打开
- package com.geanyan.udpchatwithpc;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import my.test.R;
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.TextView;
- public class MainActivity extends Activity {
- private final String DEBUG_TAG = "Sample_5_1";
- private EditText mEditText = null;
- private Button mButton = null;
- private TextView mTextView = null;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mButton = (Button) findViewById(R.id.btnSendMsg);
- mTextView = (TextView) findViewById(R.id.txtInfo);
- mEditText = (EditText) findViewById(R.id.edtTxtMsg);
- mButton.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- try {
- byte[] buffer = new byte[1024];
- String str = mEditText.getText().toString();
- //mEditText.setText("");
- buffer = str.getBytes();
- DatagramSocket socket = new DatagramSocket(8889);
- InetAddress serverAddress = InetAddress.getByName("192.168.1.100");
- DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
- packet.setAddress(serverAddress);
- packet.setPort(10001);
- socket.send(packet);
- mTextView.append("has send");
- socket.close();
- }
- catch (Exception e) {
- Log.e(DEBUG_TAG, e.toString());
- }
- }
- });
- }
- }
192.168.1.100未电脑ip地址,打开tcp调试助手,udp监听端口为8889,点击手机发送按钮,即可收到来自手机的数据。