用UDP通信实现简单聊天程序

利用UDP通信实现简单一对一聊天,要求双方网络可以互通。程序包括:1、一个线程,发送消息(包含输入的信息),发送信息给对方,发送清理输入框消息给消息处理器。2、消息处理器,显示接收对方的信息,清空输入框,显示输入框的信息。3、一个线程,接收对方信息。

//参考《Android编程兵书》 9.3 UDP通信 p344
//MainActivit.java
package com.lmy.sample_9_2;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {
    final static int iPort =3000;
    private Handler my_handler;
    private DatagramSocket ds;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final EditText displayET = (EditText) findViewById(R.id.display);
        final EditText ipET = (EditText) findViewById(R.id.ip);
        final EditText contentET = (EditText) findViewById(R.id.input);
        Button sendBtn = (Button) findViewById(R.id.send);
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //发送消息(包含输入的信息),发送信息给对方,发送清理输入框消息。
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                String strIp = ipET.getText().toString();
                String strMsg = contentET.getText().toString();

                if (strIp.equals("") || strMsg.equals("")) {
                    Toast.makeText(MainActivity.this, "请输入对方的ip地址以及需要发送的消息", Toast.LENGTH_LONG).show();
                    return;
                }
                Message message1 = new Message();
                Bundle bundle1 = new Bundle();
                bundle1.putString("display","\nto "+strIp+":"+strMsg );
                message1.setData(bundle1);
                my_handler.sendMessage(message1);

                        byte[] buf;
                        buf = strMsg.getBytes();

                        try {
                            DatagramPacket dp = new DatagramPacket(buf, buf.length,
                                    InetAddress.getByName(strIp), iPort);
                            ds.send(dp);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Message message = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("clear", "clear");
                        message.setData(bundle);
                        my_handler.sendMessage(message);
                    }}).start();
            }
        });
        //显示接收对方的信息,清空输入框,显示输入框的信息。
        my_handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle bundle = msg.getData();
                if( bundle.containsKey("text")) {
                    String text = msg.getData().getString("text");
                    displayET.getText().append(text);
                }
                if( bundle.containsKey("clear"))  contentET.setText("");
                if ( bundle.containsKey("display")) displayET.getText().append(bundle.getString("display"));
            }
        };
        Chat_int(my_handler);
    }

    //服务器端,接收对方信息。
    private void Chat_int(final Handler handler) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                byte buf[] = new byte[924];
                try {
                    ds = new DatagramSocket(iPort);
                    DatagramPacket dp = new DatagramPacket(buf, 924);
                    while (true) {
                        ds.receive(dp);
                        String text = "\nfrom " + dp.getAddress().getHostAddress()
                                + ":" + new String(buf, 0, dp.getLength());
                        System.out.println(text);

                        Message message = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("text", text);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}



    
    

        
    

    


    

    



    
    
        
            
                

                
            
        
    

 

你可能感兴趣的:(实例,代码)