简体   繁体   English

Java套接字编程回调

[英]Java socket programming call back

I have created a class library project "Communication" which is for communicating using UDP socket programming.我创建了一个类库项目“通信”,用于使用 UDP 套接字编程进行通信。

This communication will be invoked from application and made communication as always open and ready to accept using thread.此通信将从应用程序调用,并使通信始终打开并准备使用线程接受。

When ever data has to be sent, Since Application has the Communication object, its simple and easy to access.当需要发送数据时,由于 Application 有 Communication 对象,因此访问起来很简单。

But whenever a data is received, I want data to be sent to application.但是每当收到数据时,我都希望将数据发送到应用程序。

refer pic below.参考下图。

How to achieve this?, delegates?如何实现这一目标?,代表们?

查询图片

Make an interface such as this:制作一个这样的界面:

interface Notifyable {
  void notify(DatagramPacket p);
}

and let your Application implement it.并让您的Application实现它。

Then give your Communication class the reference to Application and whenever you receive data, call the notify method.然后为您的Communication类提供对Application的引用,并且每当您收到数据时,调用notify方法。

UDP communication should work the same in both directions. UDP 通信在两个方向上的工作方式应该相同。 There is no asymmetric client/server nor sender/receiver.没有非对称客户端/服务器,也没有发送方/接收方。 Your "Application" and "Communication" should work the same way.您的“应用程序”和“通信”应该以相同的方式工作。

Both can send messages and both can receive them in the same manner.两者都可以发送消息,也可以以相同的方式接收消息。

In other words, you should have written this code already on the listening side, you just need the same listening side on the "Application"换句话说,您应该已经在侦听端编写了此代码,您只需要在“应用程序”上使用相同的侦听端

What you are describing fits perfectly into http protocol.您所描述的内容完全符合 http 协议。 In HTTP the server receives a request and sends a response to the client.在 HTTP 中,服务器接收请求并向客户端发送响应。 So unless you have a specific requirement to use UDP the simplest servlet would give you a desired behavior - Server is always up and available and upon receiving an HTTP request your servlet would send a response.因此,除非您有使用 UDP 的特定要求,否则最简单的 servlet 将为您提供所需的行为 - 服务器始终处于运行状态且可用,并且在收到 HTTP 请求时,您的 servlet 将发送响应。 So, just read up how to get some Web Server or application Server and create a servlet and you are all set.因此,只需阅读如何获取一些 Web 服务器或应用程序服务器并创建一个 servlet,就可以了。 For simplicity I would recommend using Apache Tomcat as your server.为简单起见,我建议使用 Apache Tomcat 作为您的服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM