使用UDP将数据从Android设备发送到计算机

时间:2014-11-18 20:06:55

标签: java android network-programming udp

我希望将Android设备捕获的实时图像发送到运行UDP服务器的计算机。我希望使用像String这样的简单数据来启动这个项目。但是,我无法从Android设备向Netbeans中运行UDP服务器的计算机发送字符串。

Android代码 - 客户端:(此代码位于on按钮单击侦听器中)

try {
        InetAddress address = InetAddress.getByName("localhost");
        byte[] sendData = new byte[1024];
        sendData = "Hello Server".getBytes();

        DatagramSocket datagramSocket = new DatagramSocket();
        DatagramPacket datagramPacket = new DatagramPacket(sendData, sendData.length, address, 2222);
        Log.i("","Client Created");

        datagramSocket.send(datagramPacket);
        Log.i("", "Datagaram Packet Sent");

    } catch (Exception ex) {
    }

PC上的Java代码 - 服务器:

public class Server {

public static void main(String[] args) {
    try {
        byte[] receiveData = new byte[1024];

        DatagramSocket datagramSocket = new DatagramSocket(2222);
        DatagramPacket datagramPacket = new DatagramPacket(receiveData, receiveData.length);

        datagramSocket.receive(datagramPacket);
        System.out.println("Datagram Packet Received");

        String message = new String(datagramPacket.getData());
        System.out.println(message);
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}
}

0 个答案:

没有答案