android学习日记——基于UDP的聊天demo

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.ytdb.demo.MainActivity">

    <EditText
        android:id="@+id/edit_ip"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:hint="IP地址" />

    <EditText
        android:id="@+id/edit_port"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:hint="端口号"
        android:text="1026" />

    <TextView
        android:id="@+id/text_chat"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="7"
        android:textSize="20sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/edit_content"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="5"
            android:hint="请输入文字" />

        <Button
            android:id="@+id/bt_send"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="发送" />
    </LinearLayout>
</LinearLayout>

java文件

package com.ytdb.demo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class MainActivity extends Activity implements View.OnClickListener {
    private TextView text_chat;
    private EditText edit_ip;
    private EditText edit_port;
    private EditText edit_content;
    private Button bt_send;
    private StringBuffer sb = new StringBuffer();  //缓存收到的数据
    private String address;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edit_ip = (EditText) findViewById(R.id.edit_ip);
        edit_port = (EditText) findViewById(R.id.edit_port);
        edit_content = (EditText) findViewById(R.id.edit_content);
        text_chat = (TextView) findViewById(R.id.text_chat);
        bt_send = (Button) findViewById(R.id.bt_send);
        reciveData();
        bt_send.setOnClickListener(this);
        new Thread(new Runnable() {
            @Override
            public void run() {//开启一个线程判断是否有用户输入
                while (true) {
                    String con = edit_content.getText().toString().trim();
                    Message msg = Message.obtain();
                    if (!TextUtils.isEmpty(con)) {
                        msg.what = 0x111;
                        handler_input.sendMessage(msg);
                    } else {
                        msg.what = 0x222;
                        handler_input.sendMessage(msg);
                    }

                }
            }
        }).start();
    }

    public void reciveData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    byte buff[] = new byte[8192];  //存放接收到的数据最大容量8MB
                    DatagramSocket socket = new DatagramSocket(1026); //监听port接收客户端数据(自己指定)
                    DatagramPacket packet = new DatagramPacket(buff, buff.length);
                    while (true) {
                        socket.receive(packet); //接收客户端的数据报
                        String con = new String(packet.getData());
                        if (!TextUtils.isEmpty(con)) {
                            address = packet.getAddress().toString();
                            Message msg = Message.obtain();
                            msg.obj = con;
                            handler.sendMessage(msg);     //发送从远程客户端接收的数据到消息队列
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }).start();
    }


    @Override
    public void onClick(View v) {
        final String ip = edit_ip.getText().toString().trim();     //获取用户的输入的ip地址
        final String port = edit_port.getText().toString().trim();  //获取用户的输入的端口号
        final String content = edit_content.getText().toString().trim();//获取用户的发送内容
        if (!TextUtils.isEmpty(ip) && !TextUtils.isEmpty(port)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Integer p = Integer.parseInt(port);
                        InetAddress inetAddress = InetAddress.getByName(ip);
                        DatagramPacket packet = new DatagramPacket(content.getBytes(), content.getBytes().length, inetAddress, p);
                        DatagramSocket socket = new DatagramSocket();
                        socket.send(packet);  //发送数据报
                        sb.append("本机-->" + content + "\n");  //本机发送的消息
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();


        } else
            Toast.makeText(this, "ip地址或port不能为空", Toast.LENGTH_LONG).show();
        edit_content.setText(""); //清空发送消息的编辑框
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String con = (String) msg.obj;
            sb.append(address+ "-->" + con + "\n");
            text_chat.setText(sb);
        }
    };
    private Handler handler_input = new Handler() {
        @Override
        public void handleMessage(Message msg) {         //根据接收的消息判断是否获取按钮焦点
            if (msg.what == 0x111) {
                bt_send.setEnabled(true);
            } else if (msg.what == 0x222) {
                bt_send.setEnabled(false);
            }
        }
    };

}

最后记住加上网络权限<uses-permission android:name="android.permission.INTERNET"></uses-permission>

注:此demo只能实现纯文本的聊天对话功能,能在内网下使用(亲测),公网上应该需要一个固定ip,目前没试过。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值