【问题标题】:Android - Convert TCP Client to UDP ClientAndroid - 将 TCP 客户端转换为 UDP 客户端
【发布时间】:2017-10-07 07:40:01
【问题描述】:

我有一个通过发送和接收运行 TCP 连接的工作代码。 这是我的 CreateCommThreadTask 、 WriteToServer 和 CloseSocketTask 课程:

    private class CreateCommThreadTask extends AsyncTask
        <Void, Integer, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        try {
            //---create a socket---
            serverAddress =
                    InetAddress.getByName("192.168.4.1");
            socket = new Socket(serverAddress, 8080);
            commsThread = new CommsThread(socket);
            commsThread.start();
        } catch (UnknownHostException e) {
            Log.d("Sockets", e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d("Sockets", e.getLocalizedMessage());
        }
        return null;
    }
}

private class WriteToServerTask extends AsyncTask
        <byte[], Void, Void> {
    protected Void doInBackground(byte[]...data) {
        commsThread.write(data[0]);
        return null;
    }
}

private class CloseSocketTask extends AsyncTask
        <Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        try {
            socket.close();
        } catch (IOException e) {
            Log.d("Sockets", e.getLocalizedMessage());
        }
        return null;
    }
}

通过这个类,我可以读取传入的数据:

public class CommsThread extends Thread {
private final Socket socket;
private final InputStream inputStream;
private final OutputStream outputStream;

public CommsThread(Socket sock) {
    socket = sock;
    InputStream tmpIn = null;
    OutputStream tmpOut = null; 
    try {
        //---creates the inputstream and outputstream objects
        // for reading and writing through the sockets---
        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {
        Log.d("SocketChat", e.getLocalizedMessage());
    } 
    inputStream = tmpIn;
    outputStream = tmpOut;
}

public void run() {
    //---buffer store for the stream---
    byte[] buffer = new byte[1024];

    //---bytes returned from read()---
    int bytes;  

    //---keep listening to the InputStream until an 
    // exception occurs---
    while (true) {
        try {
            //---read from the inputStream---
            bytes = inputStream.read(buffer);

            //---update the main activity UI---
            SocketsActivity.UIupdater.obtainMessage(
                0,bytes, -1, buffer).sendToTarget();
        } catch (IOException e) {
            break;
        }
    }
}

//---call this from the main activity to 
// send data to the remote device---
public void write(byte[] bytes) {
    try {
        outputStream.write(bytes);
    } catch (IOException e) { }
}

//---call this from the main activity to 
// shutdown the connection--- 
public void cancel() {
    try {
        socket.close();
    } catch (IOException e) { }
}

}

最后我使用Handler 像这样使用收到的数据:

    static Handler UIupdater = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        int numOfBytesReceived = msg.arg1;
        byte[] buffer = (byte[]) msg.obj;


        //---convert the entire byte array to string---
        //---extract only the actual string received---
        if(numOfBytesReceived>0)
        {
            strReceived = new String(buffer);
            strReceived = strReceived.substring(0, numOfBytesReceived);
        }
        //---display the text received on the TextVie*---

    }
};

这些代码在 TCP 连接中运行良好。我的问题是将这些转换为 UDP 客户端需要进行哪些更改? 我想在AsyncTask 中实现UDP,就像我写的TCP 代码一样。

【问题讨论】:

    标签: java android sockets tcpclient udpclient


    【解决方案1】:

    要使用UDP,你应该使用DatagramSocket

    发送消息:

    DatagramSocket serverSocket = new DatagramSocket();
    InetAddress IPAddress = InetAddress.getByName(ipAddress);
    byte[] sendData = message.getBytes();
    DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
    serverSocket.send(sendPacket);
    

    要接收消息:

    byte[] receiveData = new byte[15]; //max length 15.
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    DatagramSocket clientSocket = new DatagramSocket(port);
    clientSocket.receive(receivePacket);
    String receivedMessage = new String(receivePacket.getData()).trim();
    

    【讨论】:

    • 我怎样才能像我写的 TCP 代码一样使用它? (AsyncTask)
    【解决方案2】:

    您应该使用DatagramSocket 和DatagramPacket。这是一个很好的教程 - Writing a Datagram Client and Server。

    【讨论】:

      【解决方案3】:

      TCP 和 UDP 的一个主要区别是 TCP 是一个连接的套接字,你首先需要建立一个连接,然后发送或接收数据包。 使用 UDP 时,您直接将数据包发送到 IP + 目标端口而没有先前的连接,它是一个未连接的套接字。

      UDP 包大小有限制,建议不要超过 512 字节,而 TCP 则没有限制。

      UDP 不能保证对方会收到数据包,发送方也不会确认是否收到,而 TCP 有这样的验证。

      如果您需要确保发送的字节在另一端收到的连接,则需要使用 TCP 而不是 UDP

      还要注意,实际上有些手机公司不再为客户分配任何公共 IP,而是分配私有 IP。在这种情况下,Android 设备无法充当服务器,这意味着无法等待接收到的 UDP 数据包,也无法侦听传入的 TCP 连接,因为它的端口无法从 WAN 访问。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-18
        • 2018-09-05
        • 2012-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-07
        相关资源
        最近更新 更多