java - Android - 将 TCP 客户端转换为 UDP 客户端

标签 java android sockets tcpclient udpclient

我有一个使用发送和接收运行 TCP 连接的工作代码。 这是我的 CreateCommThreadTaskWriteToServerCloseSocketTask 类:

    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 代码一样。

最佳答案

要使用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();

关于java - Android - 将 TCP 客户端转换为 UDP 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46617879/

相关文章:

java.lang.RuntimeException : Unable to start activity ComponentInfo java. lang.nullpointerException新手代码

android - 可以发布主题有多个订阅者

sockets - 关于 UDP 服务器如何将响应发送回 UDP 客户端的困惑

Linux。 SOL_NETLINK 未定义

node.js - socket.io/?EIO=3&transport=polling&t=1345678 不充电

java - 为什么 if 语句不起作用?

java - 将 JSONObject 发布到 Restful Web 服务时出现 400

java - 这里应该使用什么数据类型来接受来自服务器的响应

java - 如何将换行符添加到多树的toString

java - Thread.sleep 没有被 PowerMockito mock