且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java:多线程& UDP套接字编程

更新时间:2022-04-25 08:35:55

第一件事是第一件事:你的课程应该以 Java命名约定


类名应该是名词,与第一个类似每个内部单词大写的
的字母。尝试
保持你的类名简单,
描述。使用整个单词 - 避免使用
首字母缩略词和缩写词(除非
缩写比使用长格式更广泛地使用
,例如URL或
HTML)。

Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).

第二:
尝试将代码分解为连贯的部分并围绕一些常见功能进行组织。处理...可能围绕您正在编程的功能或模型。

Second: Try to break down the code into coherent sections and organize them around some common feature that you're dealing with... perhaps around the functionality or the model you're programming.

服务器的(基本)模型是 only 它做的是接收套接字连接......服务器依靠处理程序来处理这些连接,就是这样。如果您尝试构建该模型,它将如下所示:

The (basic) model for the server is that the only thing it does is receive socket connections... the server relies on a handler to handle those connections and that's it. If you try to build that model it would look something like this:

class Server{
    private final ServerSocket serverSocket;
    private final ExecutorService pool;

    public Server(int port, int poolSize) throws IOException {
      serverSocket = new ServerSocket(port);
      pool = Executors.newFixedThreadPool(poolSize);
    }

    public void serve() {
      try {
        while(true) {
          pool.execute(new Handler(serverSocket.accept()));
        }
      } catch (IOException ex) {
        pool.shutdown();
      }
    }
  }

  class Handler implements Runnable {
    private final Socket socket;
    Handler(Socket socket) { this.socket = socket; }
    public void run() {
      // receive the datagram packets
    }
 }

第三:我建议您查看一些现有示例。

Third: I would recommend that you look at some existing examples.

  • Multi-threaded Client/Server Applications:
    http://www.ase.md/~aursu/ClientServerThreads.html
  • Doug Lea:
    http://www.developer.com/java/ent/article.php/3645111/Java-5s-BlockingQueue.htm (thanks to John)
    http://gee.cs.oswego.edu/dl/cpj/index.html (still can't find the exact example, but it's there somewhere... if you feel brave look over his allcode.java file).
  • Concurrency in Practice examples:
    http://www.javaconcurrencyinpractice.com/listings.html
  • Java Concurrency Tutorials:
    http://java.sun.com/docs/books/tutorial/essential/concurrency/

每条评论更新:

好​​的Ravi,有一些问题你的代码和一些次要的问题:

Updated per comments:
OK Ravi, there are some big issues with your code and some minor issues with it:


  1. 我假设接收类是您的客户端...您应该将其作为一个单独的程序(具有自己的主类)并同时运行您的服务器和多个客户端。从您的服务器为您发送的每个新UDP包生成一个新的客户端线程是一个令人不安的想法(问题)。

  1. I assume that the Receive class is your client... you should pull that out as a separate program (with its own main class) and run your server and multiple clients at the same time. Spawning a new "client thread" from your server for every new UDP package you send is a disturbing idea (big issue).

当你制作客户端应用程序时,你应该让它在自己的中运行接收代码,同时循环(次要问题),例如:

When you make your client application, you should make it run the receiving code in its own while loop (minor issue), e.g.:

public class Client extends Thread
{
    public Client(/*..*/)
    {
        // initialize your client
    }

    public void run()
    {
        while(true)
        {
            // receive UDP packets
            // process the UDP packets
        }
    }

    public static void main(String[] args) throws IOException
    {
        // start your client
        new Client().start();
    }
}


  • 你应该只需要一个线程客户端和每个服务器一个线程(你在技术上甚至没有单独的线程,因为main有自己的线程),所以你可能找不到有用的 ExecutorService

    否则你的方法是正确的......但是我仍然建议你检查一些例子。

    Otherwise your approach is correct... but I would still recommend that you check out some of examples.