java对等使用UDP套接字

标签 java multithreading sockets concurrency udp

我有一个用 java 编写的简单的点对点程序。我有以下代码。

import java.net.*;
import java.io.*;
public class Broadcasts {

private final Runnable receiver;
private final Runnable sender;
private boolean run = true;


  public Broadcasts(UDPSocketHandler parent)  throws UnknownHostException{
    InetAddress aHost = InetAddress.getLocalHost();

    sender = new Runnable() {
        public void run() {
            byte data[] = "Hello".getBytes();
            DatagramSocket socket = null;
            try {
                socket = new DatagramSocket();
            } catch (SocketException ex) {
                ex.printStackTrace();
                parent.quit();
            }

            DatagramPacket packet = new DatagramPacket(
                    data,
                    data.length,
                    aHost,
                    9090);
            while (run) {
                try {

                    System.out.println("what is sent"+new String(packet.getData()));
                    socket.send(packet);
                    Thread.sleep(1000);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    parent.quit();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                    parent.quit();
                }
            }
        }
    };


    receiver = new Runnable() {
        public void run() {
            byte data[] = new byte[0];
            DatagramSocket socket = null;
            try {
                socket = new DatagramSocket(9090);
            } catch (SocketException ex) {
                ex.printStackTrace();
                //parent.quit();
            }
            DatagramPacket packet = new DatagramPacket(data, data.length);
            //System.out.println("this is what has been received"+packet.getData());
            String temp;
           // while (run) {
                try {
                    socket.receive(packet);
                    System.out.println("this is what has been received"+packet.getData());

                    //System.out.println("Message received ..."+ temp);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    parent.quit();
                }

            //}
        }
    };


    new Thread(sender).start();
    new Thread(receiver).start();

}

  public void quit() {
    run = false;
  }
}

然后我有下面的类来处理我的通信

public class UDPSocketHandler {

  private final Broadcasts broadcasts;
// continue running application?
  private boolean run = true;

  public UDPSocketHandler() throws UnknownHostException
  {
    // start socket server to accept incoming connections
    new Thread().start();


    // late initialize of UDP broadcast and receive, to ensure needed
    // objects are instantiated
    broadcasts = new Broadcasts(this);
}

// global quit method shuts down everything and exits
public void quit() {
    run = false;
    broadcasts.quit();
    System.exit(0);
}

// application entry
  public static void main(String[] args) throws UnknownHostException{
   new UDPSocketHandler();

  }
}

问题是接收者没有收到任何东西。据我了解,我们可以在与此 question 所示的相同程序上运行发送方和接收方.这实际上是我想做的,但使用 UDP 而不是 TCP。我的代码有什么问题?

最佳答案

经过一些努力和几个小时后,我终于设法让我的程序运行起来。我有以下内容:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.*;

public class SocketTest {
  private boolean run = true;


  public static void main(String[] args) throws IOException {

    startServer();
    startSender();
  }

  public static void startSender() throws UnknownHostException{
    InetAddress aHost = InetAddress.getLocalHost();
    (new Thread() {
        @Override
        public void run() {
            byte data[] = "Hello".getBytes();
            DatagramSocket socket = null;
            try {
                socket = new DatagramSocket();
                socket.setBroadcast(true);
            } catch (SocketException ex) {
                ex.printStackTrace();
                //parent.quit();
            }

            DatagramPacket packet = new DatagramPacket(
                    data,
                    data.length,
                    aHost,
                    9090);
            int i=0;
            while (i<10) {
                try {

                    System.out.println("what us mmmm.."+new String(packet.getData()));
                    socket.send(packet);
                    Thread.sleep(50);
                    i++;
                    System.out.println(i);
                } catch (IOException ex) {
                    ex.printStackTrace();
                   // parent.quit();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                   // parent.quit();
                }
            }
        }}).start();
    }


  public static void startServer() {
    (new Thread() {
        @Override
        public void run() {

                //byte data[] = new byte[0];
                DatagramSocket socket = null;
                try {
                    socket = new DatagramSocket(9090);
                    //socket.setBroadcast(true);;

                } catch (SocketException ex) {
                    ex.printStackTrace();
                    //parent.quit();
                }
                DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
                //System.out.println("this is what has been received111"+packet.getData());
                String temp;
                while (true) {
                try {
                    socket.receive(packet);
                    temp=new String(packet.getData());
                    System.out.println("this is what has been received"+temp);


                    //System.out.println("Message received ..."+ temp);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    //parent.quit();
                }

                 }
            }

    }).start();
 }
}

通过这段代码,每个节点都可以充当客户端和服务器。我们所要做的就是传递我们正在向其发送请求的服务器的正确端口号。在此示例代码中,端口号与客户端向自己发送数据包的端口号相同。我希望这可以帮助其他人

关于java对等使用UDP套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40044453/

相关文章:

database - 关于使用 Delphi XE2 进行数据库编程的问题

java - 撰写消息错误。 "Before start of ResultSet."

java - 尝试对按各自顺序给定的字符串进行排序,无法使用集合

java - 为什么同步的 getter 像 volatile read 一样工作?

c - 从snort数据包中获取IP地址-UNSOCK

c++ - boost ASIO socket 是否自动使用多个网络接口(interface)?有效率的?如果没有,怎么办?

java - 将带有映射的对象列表转换为基元数组

JAVA : possible loss of precision

c++ - fork 时哪些系统和库调用是安全的?

multithreading - 更快的 TMultiReadExclusiveWriteSynchronizer?