SocketUDP

MainActivity内容

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    UdpReadThread mReadThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mReadThread = new UdpReadThread();
        mReadThread.startListen();
    }

    private void senMsg(){
        mReadThread.sendMessage( "192.168.1.14","client1","hello");
    }


    public void onClick(View view) {
        senMsg();
    }
}

UdpClient内容

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * @author alice
 * @version 1.0
 * @Date 2017/10/15 20:43
 */
public class UdpClient {


    public static void sendPackage(DatagramSocket socket, String friendIP, String from, String msg){
        try {
            //服务器ip
            InetAddress serverAddress = InetAddress.getByName("192.168.1.9");
            //Inet4Address serverAddress = (Inet4Address) Inet4Address.getByName("192.168.1.32");
            String str = friendIP + ":" + from + ":" + msg;//设置要发送的报文
            byte data[] = str.getBytes();//把字符串str字符串转换为字节数组
            //创建一个DatagramPacket对象,用于发送数据。
            //参数一:要发送的数据  参数二:数据的长度  参数三:服务端的网络地址  参数四:服务器端端口号
            DatagramPacket packet = new DatagramPacket(data, data.length ,serverAddress ,10025);
            socket.send(packet);//把数据发送到服务端。
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

UdpReadThread内容

import android.util.Log;

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

/**
 * @author alice
 * @version 1.0
 * @Date 2017/10/15 20:35
 */
public class UdpReadThread {
    DatagramSocket socket;
    private byte data[];
    DatagramPacket packet;
    private boolean isLive;
    public UdpReadThread(){
        try {
            socket = new DatagramSocket(1889);
            //创建一个byte类型的数组,用于存放接收到得数据
            data= new byte[4 * 1024];
            packet = new DatagramPacket(data,data.length);
        }catch (Exception e){

        }
    }

    public void startListen(){
        isLive = true;
            new Thread(){
                @Override
                public void run() {
                    try {
                        while (isLive) {
                            socket.receive(packet);
                            //把客户端发送的数据转换为字符串。
                            onReceiveMsg(packet);
                            Thread.sleep(10);
                        }
                        socket.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {

                    }
                }
            }.start();

    }

    private void onReceiveMsg(DatagramPacket packet){
        //使用三个参数的String方法。参数一:数据包 参数二:起始位置 参数三:数据包长
        String result = new String(packet.getData(), packet.getOffset(), packet.getLength());
        Log.d("sxl", "sxl onReceiveMsg result="+result);
    }

    public void stop(){
        isLive = false;
    }

    /**
     * 客户端发送数据
     * @param friendIP 好友的ip
     * @param from 我的昵称
     * @param msg 消息
     */
    public void sendMessage( final String friendIP,final String from, final String msg) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                UdpClient.sendPackage(socket,friendIP, from, msg);
            }
        }.start();
    }
}

activity_main布局

<RelativeLayout
    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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="alice.bw.com.socketudpclicent_1.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:onClick="onClick"
        android:layout_marginTop="95dp"/>
</RelativeLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值