从Java中的单个DatagramSocket发送和接收

时间:2013-11-04 22:43:40

标签: java multithreading sockets

是否可以使用单个DatagramSocket在单个Java应用程序中发送和接收数据包?我一直试图用线程做这个,但没有运气。我在网上找到的每个套接字教程使用单独的客户端和服务器类来发送数据但是,就我而言,我希望客户端和服务器驻留在单个应用程序中。以下是我的尝试:

public class Main implements Runnable {

// global variables
static DatagramSocket sock;
String globalAddress = "148.61.112.104";
int portNumber = 9876;

byte[] receiveData = new byte[1024];

public static void main(String[] args) throws IOException {
    sock = new DatagramSocket();

    (new Thread(new Main())).start();

    // send data
    while (true) {
        InetAddress IPAddress = InetAddress.getByName("127.0.0.1");
        int port = 9876;
        int length = 1024;


        byte [] sendData = new byte[1024];
        String message = "hello";

        sendData = message.getBytes();

        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                IPAddress, port);

        sock.send(sendPacket);

    }
}

public void run() {
    //get incoming data
    while (true) {
        byte[] sendData = new byte[1024];

        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                receiveData.length);

        receivePacket.setPort(portNumber);

        try {
            sock.receive(receivePacket);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String sentence = new String(receivePacket.getData());
        System.out.println("RECEIVED: " + sentence);
    }
}

}

正如您所看到的,我在主线程上的循环中发送数据,并在可运行线程中接收循环上的数据。主线程应该不断地向接收器发送“hello”并输出消息。但是,没有输出?

我在这里走在正确的轨道上吗?使用线程是最好的方法吗?这甚至可能吗?如果是这样,有更好的解决方案吗?

0 个答案:

没有答案