java中异步socket类的实现和源代码
java 实现异步的几种案例方法

java 实现异步的几种案例方法Java是一种高级编程语言,它具有强大的异步编程能力。
在Java中,实现异步编程的方法有很多种,下面将介绍几种常见的实现异步编程的方法。
1. 使用Future和Callable接口Future和Callable接口是Java中实现异步编程的基础。
Callable接口定义了一个带有返回值的任务,而Future接口则表示一个异步计算的结果。
通过将Callable任务提交给ExecutorService线程池,可以异步执行任务,并通过Future接口获取任务的结果。
例如,下面的代码演示了如何使用Future和Callable接口实现异步编程:```ExecutorService executor =Executors.newSingleThreadExecutor();Future<String> future = executor.submit(new Callable<String>() {public String call() throws Exception {// 执行异步任务return "异步任务执行完成";}});// 获取异步任务的结果String result = future.get();```2. 使用CompletableFuture类CompletableFuture类是Java 8中新增的一个类,它提供了更加灵活和强大的异步编程能力。
通过CompletableFuture类,可以将多个异步任务组合起来,实现更加复杂的异步编程逻辑。
例如,下面的代码演示了如何使用CompletableFuture类实现异步编程:```CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {// 执行异步任务return "异步任务执行完成";});future.thenAccept(result -> {System.out.println(result);});```3. 使用RxJava库RxJava是一个基于观察者模式的异步编程库,它提供了丰富的操作符和组合方式,可以轻松地实现复杂的异步编程逻辑。
Socket调用方式(同步,异步,阻塞,非阻塞)

Socket调⽤⽅式(同步,异步,阻塞,⾮阻塞)同步:我调⽤⼀个功能,该功能没有结束前,我死等结果。
异步:当⼀个异步过程调⽤发出后,调⽤者不能⽴刻得到结果。
该功能在完成后,通过状态、通知和回调来通知调⽤者。
同步和⾮同步关注的是调⽤者是否等待等待调⽤结果。
举个通俗的例⼦:你打电话问书店⽼板有没有《分布式系统》这本书,如果是同步通信机制,书店⽼板会说,你稍等,”我查⼀下",然后开始查啊查,等查好了(可能是5秒,也可能是⼀天)告诉你结果(返回结果)。
⽽异步通信机制,书店⽼板直接告诉你我查⼀下啊,查好了打电话给你,然后直接挂电话了(不返回结果)。
然后查好了,他会主动打电话给你。
在这⾥⽼板通过“回电”这种⽅式来回调。
阻塞:调⽤我(函数),我(函数)没有接收完数据或者没有得到结果之前,我不会返回。
⾮阻塞:调⽤我(函数),我(函数)⽴即返回通知调⽤者以最常⽤的send和recv两个函数为例⽐如你调⽤send函数发送⼀定的Byte,在系统内部send做的⼯作其实只是把数据传输(Copy)到TCP/IP协议栈的输出缓冲区,它执⾏成功并不代表数据已经成功的发送出去了,如果TCP/IP协议栈没有⾜够的可⽤缓冲区来保存你Copy过来的数据的话...这时候就体现出阻塞和⾮阻塞的不同之处了:对于阻塞模式的socket send函数将不返回直到系统缓冲区有⾜够的空间把你要发送的数据Copy过去以后才返回,⽽对于⾮阻塞的socket来说send会⽴即返回WSAEWOULDDBLOCK告诉调⽤者说:"发送操作被阻塞了!!!你想办法处理吧..."对于recv函数,同样道理,对于阻塞模式的socket来说如果TCP/IP协议栈的接收缓冲区没有通知⼀个结果给它它就⼀直不返回:耗费着系统资源....对于⾮阻塞模式的socket该函数会马上返回,然后告诉你:WSAEWOULDDBLOCK---"现在没有数据,回头再来看看"阻塞I/O模型:⾮阻塞I/O模型:阻塞和⾮阻塞关注的是调⽤者在等待调⽤结果时的状态。
java异步原理

java异步原理
Java中的异步原理是通过多线程实现的。
在传统的同步编程中,代码是按照顺序执行的,遇到阻塞操作时会发生阻塞,直到操作完成才会继续执行下一行代码。
而异步编程则可以在进行阻塞操作时,不必等待结果返回,而是可以继续执行后续的代码逻辑。
Java中异步编程常用的方式有使用线程池和Future,以及Java 8以后引入的CompletableFuture。
使用线程池和Future可以通
过submit方法提交任务到线程池中,返回一个Future对象,
通过该对象可以在需要的时候获取异步任务的结果。
当需要获取异步任务的结果时,可以通过调用Future对象的get方法来
阻塞等待结果返回。
CompletableFuture是Java 8引入的新特性,用于简化异步编程的复杂性。
它可以通过一系列的操作链来实现异步任务之间的依赖关系,如thenApply、thenAccept、thenCompose等方法。
通过这些方法可以实现任务的串行执行,也可以实现任务的并行执行。
CompletableFuture还提供了各种回调方法和异常处理方法,可以方便地处理异步任务的结果。
在异步编程中,需要注意处理线程安全问题。
多线程同时访问共享的资源时,可能会导致数据不一致或者线程安全问题。
可以通过使用锁机制或者使用线程安全的数据结构来解决这些问题。
总之,Java中的异步编程通过多线程实现,可以通过线程池和
Future、CompletableFuture等方式来实现异步任务的执行和结果的处理。
同时需要注意处理线程安全问题。
java 不同系统之间传输数据的方法

java 不同系统之间传输数据的方法Java是一种强大且广泛应用的编程语言,用于开发各种类型的应用程序。
在实际开发中,经常需要在不同的系统之间传输数据。
本文将介绍一些常用的方法来实现Java不同系统之间的数据传输。
1. 使用Socket通信Socket通信是一种常用的网络通信方式,可以实现不同系统之间的数据传输。
通过Socket,我们可以在客户端和服务器之间建立一条双向通道进行数据交换。
在Java中,可以使用Java的原生Socket库来实现Socket通信。
客户端和服务器端通过准确的IP地址和端口号来建立连接。
客户端可以使用Socket类来与服务器进行通信,而服务器则使用ServerSocket类监听并接受客户端连接。
2. 使用HTTP协议HTTP协议是一种应用层协议,常用于Web应用程序中。
通过HTTP协议,不同系统之间可以通过发送和接收HTTP请求和响应来进行数据传输。
在Java中,可以使用Java的HttpURLConnection类或者第三方库,如Apache 的HttpClient来实现HTTP通信。
通过发送HTTP请求,可以将数据以请求参数或JSON/XML等格式发送到目标系统,并接收目标系统的HTTP响应。
3. 使用WebServiceWebService是一种通过网络进行通信的软件系统。
它可以使不同系统之间的应用程序通过Web服务接口进行数据传输和交互。
在Java中,可以使用Java的JAX-WS和JAX-RPC等API来开发和使用WebService。
通过定义WebService接口和实现相应的服务端和客户端,可以在不同系统之间轻松地传输数据。
4. 使用消息队列消息队列是一种常用的异步通信方式,允许不同系统之间以消息的形式传递数据。
消息队列将数据发送方发送的消息存储在队列中,接收方从队列中接收并处理消息。
在Java中,可以使用ActiveMQ、RabbitMQ等消息中间件来实现消息队列。
java异步处理方法

java异步处理方法在Java中,异步处理方法允许程序在执行任务时不必等待结果返回,而是继续执行其他操作。
这种方式可以提高程序的性能和响应能力,特别适用于处理需要等待较长时间才能完成的任务,比如网络请求、文件读写、数据库操作等。
Java提供了多种处理异步任务的机制。
下面是几种常用的方法:1. 线程池(ThreadPoolExecutor):使用线程池可以方便地管理和复用线程。
可以使用java.util.concurrent包中的ThreadPoolExecutor来创建一个线程池,并提交任务给线程池进行处理。
线程池会自动分配线程来执行任务,并在任务完成后将结果返回。
2. CompletableFuture:这是Java 8引入的一种新的异步编程方式。
CompletableFuture类提供了一系列方法来处理异步任务的执行结果。
它可以通过thenApply()、thenAccept()、thenRun()等方法来指定任务完成后的处理操作,也可以通过thenCompose()、thenCombine()等方法来组合多个异步任务。
3. 回调函数(Callback):回调函数是一种常见的异步编程模式,它可以在任务完成后回调指定的方法。
在Java中,可以使用接口作为回调函数的实现,将任务的结果传递给回调方法进行处理。
4. CompletableFuture与回调函数的结合:CompletableFuture类可以与回调函数相结合使用,实现更加灵活的异步处理方式。
可以使用thenApplyAsync()、thenAcceptAsync()等方法指定任务完成后的回调函数,并通过supplyAsync()、runAsync()等方法创建CompletableFuture实例。
需要注意的是,在使用异步处理方法时,需要注意线程安全性和资源管理。
确保在多线程环境下的正确性和性能。
另外,异步处理可能会导致代码逻辑的复杂性增加,需要合理设计和组织代码结构,确保代码的可读性和可维护性。
java异步编排的实现方式

java异步编排的实现方式Java异步编排是一种在多个任务之间进行协调和管理的技术,可以提高程序的执行效率和性能。
在Java中,有多种实现方式可以实现异步编排,例如使用线程池、Future和CompletableFuture等。
一、线程池线程池是一种用于管理和复用线程的机制。
在Java中,可以通过ThreadPoolExecutor类来创建和使用线程池。
线程池可以通过提供一定数量的线程来执行任务,当任务执行完毕后,线程可以被复用,避免了线程的频繁创建和销毁。
使用线程池可以实现异步编排的效果,通过提交任务到线程池中,线程池会按照一定的调度算法来执行任务,并提供一些监控和控制的机制。
二、FutureFuture是Java提供的一个接口,用于表示一个异步计算的结果。
通过Future可以获取异步计算的结果,或者取消异步计算的执行。
在Java中,可以通过ExecutorService.submit方法返回一个Future对象,然后通过Future的get方法来获取异步计算的结果。
使用Future可以实现异步编排,通过提交多个任务到线程池中,然后通过Future来获取任务的执行结果,当所有任务都执行完毕后,再进行下一步的操作。
三、CompletableFutureCompletableFuture是Java 8中引入的一个新特性,用于简化异步编程的复杂性。
CompletableFuture可以将多个异步任务串行或并行地执行,并提供了丰富的方法来处理异步任务的结果。
使用CompletableFuture可以实现更加灵活和高效的异步编排。
例如,可以使用CompletableFuture的thenCompose方法将多个任务串行执行,或者使用CompletableFuture的allOf方法来等待所有任务执行完毕后再进行下一步的操作。
总结:Java异步编排是一种提高程序执行效率和性能的技术。
在Java中,可以使用线程池、Future和CompletableFuture等方式来实现异步编排。
websocket的java写法

WebSocket是一种在单个TCP连接上进行全双工通信的协议。
它原生支持在Web浏览器和Web服务器之间进行实时数据传输。
在Java 中,我们可以使用不同的库来实现WebSocket通信。
本文将介绍WebSocket的Java写法,并提供一个示例项目来演示如何在Java中实现WebSocket。
一、WebSocket的Java库在Java中,有几个主要的库可以用来实现WebSocket通信。
其中最流行的是javax.websocket包,以及基于它的几个实现,比如Tyrus 和Tomcat。
除了这些库,还有一些第三方库,比如Java-WebSocket和Netty,也可以用来实现WebSocket通信。
二、使用javax.websocket包javax.websocket包是JavaEE 7中新增加的一个用来实现WebSocket通信的标准API。
它提供了一组接口和注解,可以让我们很容易地创建WebSocket端点和客户端。
下面是一个简单的Java WebSocket端点的例子:```javaimport javax.websocket.OnClose;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;ServerEndpoint("/websocket")public class MyWebSocket {OnOpenpublic void onOpen(Session session) {System.out.println("WebSocket opened: " + session.getId()); }OnClosepublic void onClose(Session session) {System.out.println("WebSocket closed: " + session.getId()); }}```在这个例子中,我们创建了一个名为MyWebSocket的WebSocket 端点。
socket建立tcp连接的java代码

socket建立tcp连接的java代码Socket是Java中常用的网络编程类,可以用于建立TCP连接,完成客户端和服务器间的通信。
下面是Socket建立TCP连接的Java代码:1. 建立Socket对象TCP协议在建立连接时,需要同时指定服务器的IP地址和端口号。
因此,在客户端程序中,需要先创建一个Socket对象来指定需要连接的服务器IP地址和端口号。
Socket socket=new Socke t(“192.168.1.1”, 8888);2. 获取输入输出流建立连接之后,客户端可以向服务器发送数据,还可以接收服务器返回的数据。
为了完成这些操作,需要获取输入输出流对象。
InputStream input=socket.getInputStream();OutputStream output=socket.getOutputStream();3. 发送数据客户端想要向服务器发送数据,可以通过输出流对象write()方法实现。
byte[] data=”Hello Server”.getBytes();output.write(data);4. 接收数据客户端从服务器接收数据,可以通过输入流对象read()方法实现。
byte[] buffer=new byte[1024];int len=input.read(buffer);5. 断开连接客户端和服务器通信结束之后,需要关闭连接。
input.close();output.close();socket.close();综上所述,以上代码实现了Socket建立TCP连接的过程,使得客户端和服务器能够互相通信,完成所需的业务操作。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
java中异步socket类的实现和源代码作者:dozb我们知道,java中socket类一般操作都是同步进行,常常在read的时候socket就会阻塞直到有数据可读或socket连接断开的时候才返回,虽然可以设置超时返回,但是这样比较低效,需要做一个循环来不停扫描数据是否可读。
看来,在同一个线程中,要是想实现异步读写不太容易。
下面介绍的这个类实现了伪异步socket通讯。
基本思想就是在现有socket类的基础上进行封装,当sock et连接建立成功后,立即创建一个socket数据接收线程,专门负责阻塞式的socket读取(read),而当前线程负责数据的发送(send)。
另外定义了一个接口,包括了socket的各种事件的回调。
我们要实现这个接口,在接口实现类中创建异步socket对象,并且传递接口类到异步socket对象中,目的是有socket事件的时候回调我们的方法。
下面是接口:SocketExHandler.javapackage ;import .*;/*** Title:* Description:* Copyright: Copyright (c) 2001* Company: * @author dozb* @version 1.0*//*** 异步Socket Client Interface* 使用方法:* 1.定义类 MySocketClientEx 实现SocketExHandler接口,实现 OnReceive OnClose OnConnect 事件* 2.在类中实现start方法 MySocketEx = new SocketEx(this,ip,port)* 3.在类中实现stop方法 delete MySocketEx* 4.当有数据到达时会触发OnReceive事件* 5.当对方SOCKET关闭时会触发OnClose事件* 6.当SOCKET建立时会触发OnConnect事件*//*** 异步Socket Server Interface* 使用方法:* 1.定义类 MySocketServerEx 实现SocketExHandler接口,实现 OnReceive OnListen OnClose OnAccept 事件* 2.在类中实现start方法 MySocketEx = new ServerSocketEx(this,ip,por t)* 3.在类中实现stop方法 delete MySocketEx* 4.当开始监听时会触发OnListen事件* 5.当SOCKET关闭时会触发OnClose事件* 6.当有客户端SOCKET要建立连接时会触发OnAccept事件*/public interface SocketExHandler{//当客户端sock数据到达时触发public void OnReceive(Object socket,byte buf[],int nLen);//当客户端sock连接建立成功时触发public void OnConnect(Object socket);//当服务端sock监听开始时触发public void OnListen(Object socket);//当服务端sock接受一个新的sock连接时触发public void OnAccept(Object socket,SocketEx ClientSocket) ;//当sock关闭时触发public void OnClose(Object socket);}下面是异步客户端socket类:SocketEx.javapackage ;import java.io.*;import .*;import java.util.*;import .SocketExHandler;/*** Title:* Description:* Copyright: Copyright (c) 2001* Company: * @author dozb* @version 1.0*/public class SocketEx implements Runnable{public static final boolean isdebug = true;//调试/***构造函数.*/public SocketEx(SocketExHandler seh,Socket ClientSocket){this. seh = seh;thisSocket = ClientSocket; InitNotify();}public SocketEx(SocketExHandler seh,String host,int port) thr ows IOException {this.seh = seh;thisSocket = new Socket(host,port);In itNotify();}public SocketEx(SocketExHandler seh, InetAddress address, int port ) throws IOException {this.seh = seh;thisSocket = new Socket(ad dress, port);InitNotify();}public SocketEx(SocketExHandler seh, String host, int port, I netAddress localAddr, int localPort ) throws IOException {this.seh = seh;thisSocket = new Socket(host,port,localAddr,localPort );InitNotif y();}public SocketEx(SocketExHandler seh, InetAddress address, int port, InetAddress localAddr, int localPort ) throws IOException {thi s.seh = seh;thisSocket = new Socket(address, port, localAddr,localPor t );InitNotify();}/*** 实现Socket的可见方法.*/public synchronized void close() throws IOException {IsRunni ng = false;thisSocket.close();}public InetAddress getInetAddress() {return thisSocket.getIne tAddress();}public InputStream getInputStream() throws IOException{return thisSocket.getInputStream(); }public InetAddress getLocalAddress() { r eturn thisSocket.getLo calAddress() ; }public int getLocalPort() { return thisSocket.getLocalPort() ; }public OutputStream getOutputStream() throws IOException{retu rn thisSocket.getOutputStream(); }public int getPort() { return thisSocket.getPort() ; }public int getSoLinger() throws SocketException{ return t hisSocket.getSoLinger(); }public synchronized int getSoTimeout() throws SocketException { return thisSocket.getSoTimeout(); }public boolean getTcpNoDelay() throws SocketException {return thisSocket.getTcpNoDelay(); }public void setSoLinger( boolean on, int val ) throws SocketE xception { thisSocket.setSoLinger(on,val); }public synchronized void setSoTimeout( int timeout ) throws S ocketException {thisSocket.setSoTimeout( timeout ) ; }public void setTcpNoDelay( boolean on ) throws SocketExceptio n {thisSocket.setTcpNoDelay(on); }public String toString() { return thisSocket.toString() ; }/*** 获取Socket*/public Socket GetSocket(){return thisSocket;}/*** 初始化异步Socket*/private void ShowMsg(String Msg){if(isdebug)System.out.println(Msg);}private void InitNotify(){if(NotifyThread != null) return ;try{biStream = new BufferedInputStream(getInputStr eam());thisSocket.setSoTimeout(0);}catch(IOException e){ShowMsg("InitNotify() IOException.");}IsRunning = true;NotifyThread = new Thread(this,"SocketEx_NoitfyThread ");NotifyThread.setDaemon(true);NotifyThread.start();if(seh !=null)seh.OnConnect(this);}/*** 关闭Socket*/private void Close(){try{close();}catch(Exception eclose){ShowMsg("Close() Exception.");}}protected void finalize() throws Throwable{Close();super.finalize();}/*** Thread 运行*/public void run(){while(IsRunning){try{if(getInputStream().read(buf,0,1) <= 0) //试读一个字节{DoClose();return ;}if(!DoReceive(getInputStream().availab le()))return ;}catch(Exception e){ShowMsg("run() Exception.");DoClose();return ;}try{Thread.sleep(0); //}catch(InterruptedException e){ShowMsg("run() InterruptedException. ");DoClose();return ;}}}/*** 当有数据到达时的回调方法.*/private boolean DoReceive(int nCanReadCount){try{int len = 0,nCurrReadCount=0,nStart=1;do{for(int i=nStart;i< BUFLEN;i++)buf[i]=0;if(nCanReadCount == 0){if(seh !=null)seh.OnReceive(this,buf, nStart);return true;}if(nCanReadCount >(BUFLEN-2)){nCurrReadCount = BUFLEN-2;}else{nCurrReadCount = nCanReadCount;}len = biStream.read(buf,nStart,nCurrRe adCount);if(len == 0){DoClose();return false;}nCanReadCount -= len;buf[len+nStart] = 0;if(seh !=null)seh.OnReceive(this,buf,len+nStart);nStart = 0;}while(nCanReadCount >0);}catch(Exception excpt){ShowMsg("DoReceive() Exception.");DoClose();return false;}return true;}/*** 当Socket建立连接时的回调方法.*/private void DoConnect(){if(seh !=null)seh.OnConnect(this);}/*** 当Socket关闭时的回调方法.*/private void DoClose(){try{if(IsRunning){Close();if(seh !=null)seh.OnClose(this);IsRunning = false;}}catch(Exception e){ShowMsg("DoClose() Exception.");}}/*** 以下实现不要改动!!!!*/private Thread NotifyThread=null;private boolean IsRunning = false;private Socket thisSocket = null;private static final int BUFLEN = 4097;private byte buf[] = new byte[BUFLEN];private BufferedInputStream biStream = null;private SocketExHandler seh=null;}下面是异步socketserver类:ServerSocketEx .javapackage ;import java.io.*;import .*;import java.util.*;/*** Title:* Description:* Copyright: Copyright (c) 2001* Company: * @author dozb* @version 1.0*/public class ServerSocketEx extends ServerSocket implements Runnable {/*** 以下实现不要改动!!!!*/public ServerSocketEx(SocketExHandler seh, int port ) throws IOException {super(port);this.seh = seh; Listen();}public ServerSocketEx(SocketExHandler seh, int port, int back log ) throws IOException {super(port,backlog);this.seh = seh; L isten ();}public ServerSocketEx(SocketExHandler seh, int port, int back log, InetAddress bindAddr ) throws IOException {super(port,backlog, b indAddr);this.seh = seh;Listen();}public void setTimeout(int timeout) {this.timeout = timeout;}public static Vector GetClientPool(){return ClientPool;};public static void CloseAllClients(){for(int i=0;i< ClientPool.size();i++){try{SocketEx s=(SocketEx)ClientPool.elemen tAt(i);if(s != null) s.close();}catch(Exception e){}}ClientPool.removeAllElements();}public static void PutClient(SocketEx s){ClientPool.addElemen t(s);};/*** 关闭Socket*/public void Close(){IsRunning = false;try{close();}catch(Exception eclose){}}protected void finalize() throws Throwable{Close();super.finalize();}* Thread 运行*/public void run(){while(IsRunning){acceptConnections();}DoClose();}// -------------------- Private methodsprivate void Listen() throws IOException{InitNotify();if(seh !=null)seh.OnListen(this);}/*** 初始化异步Socket*/private void InitNotify()throws IOException{if(NotifyThread != null) return ;try{setSoTimeout(this.timeout);} catch( IOException ex ) {IsRunning=false;throw ex;}IsRunning = true;NotifyThread = new Thread(this,"ServerSocketEx_Noitfy Thread");NotifyThread.setDaemon(true);NotifyThread.start();}/*** 当Socket关闭时的回调方法.private void DoClose(){try{if(seh !=null)seh.OnClose(this);//NotifyThread.stop();}catch(Exception e){}}private void processSocket(Socket s) throws IOException{SocketEx se = new SocketEx(seh,s);PutClient(se);if(seh !=null)seh.OnAccept(this,se);}private void acceptConnections() {try {if(IsRunning == false)return;Socket socket = acceptSocket();if(IsRunning != false && socket != null) {processSocket(socket);}} catch(Throwable e) {IsRunning = false;}}private Socket acceptSocket() {Socket accepted = null;try {if(IsRunning == true) {accepted = accept();if(IsRunning == false) {if(null != accepted) {accepted.close(); // rude, but un likely!accepted = null;}}}} catch(InterruptedIOException iioe) {// normal part -- should happen regularly so// that the endpoint can release if the server// is shutdown.// you know, i really wish that there was a// way for the socket to timeout without// tripping an exception. Exceptions are so// 'spensive.} catch (SocketException e) {if (IsRunning != false) {IsRunning = false;}} catch(Throwable e) {IsRunning = false;}return accepted;}private static final int TIMEOUT = 5000;private int timeout = TIMEOUT;private Thread NotifyThread=null;private boolean IsRunning=false;private SocketExHandler seh=null;private static Vector ClientPool=new Vector();}下面是几个工具类:TimerClient.javapackage com.ly.util;/*** TimerClient Interface** @version 1.0, 8 October 1995**/public interface TimerClient{void timerEvent(int id);}TimerCtl.javapackage com.ly.util;import java.util.Vector;import java.util.Enumeration;//import com.borland.jb.util.Diagnostic;/*** Timer Component** Note:* - The successful operation of this timer requires clients to exec ute simple, short* code snippets when called back by the engine. Otherwise the qu eue's delivery* mechanism will be held up** Further work:* - When Thread.Interrupt is implemented we can switch from the bus y wait model to* the calculated wait model. Without the interrupt the thread wa its for the* calculated interval before waking up. This is a problem if ano ther shorter* request arrives. For now we'll assume the minimum resolution o f the timer is* 100ms.** @version 1.0, 2 October 1995**/public class TimerCtl{static TimerTasks timerTasks;public TimerCtl() {}/** Start a timer running*/public static void startTimer(TimerClient client, int eventId, long delay, boolean repeat) {// create the timer if necessaryif (timerTasks == null) {timerTasks = new TimerTasks();timerTasks.start();}//Diagnostic.out.println("TIMER: startTimer"+eventId);// add the new task to the queuetimerTasks.add(client, eventId, delay, repeat);}/** Stop a timer*/public static void stopTimer(TimerClient client, int eventId) {//Diagnostic.out.println("TIMER: stopTimer"+eventId);if(timerTasks != null)timerTasks.end(client, eventId);}}class TimerTasks extends Thread{Vector tasks = new Vector();boolean suspended = false;boolean sleeping = false;/*** Thread task runner*/public void run() {// Loop foreverwhile (true) {long sleepTime = 0;// Ensure that the tasks class is protectedsynchronized (tasks) {//Diagnostic.out.println("TIMER: Tick");// Scan the job list for any jobs which may fire.// Mark one-shot jobs for deletion// Calculate the maximum time we can sleep forsleepTime = scan();// Delete DeletePending jobs. DeletePending jobs result from one-shots which have// been sent, and repeat jobs which have been cancelled. Job s may have been// cancelled during the Scan process.purge();}// Suspend timer if necessaryif (tasks.size() == 0) {//Diagnostic.out.println("TIMER: Suspend");try {synchronized(this) {suspended = true;wait();}}catch (InterruptedException e) {}}else {//Diagnostic.out.println("TIMER: Suggested Sleeping for "+sle epTime);if (sleepTime >= 0) {try {sleeping = true;sleep(sleepTime);sleeping = false;}catch (InterruptedException i) {//Diagnostic.out.println("TIMER: Caught me napping");}}}}}/*** Add a new task*/public void add(TimerClient client, int eventId, long delay, boolea n repeat) {TimerTask t = new TimerTask(client, eventId, delay, repeat);synchronized (tasks) {tasks.addElement((Object)t);}// Want instant response - wake the thread if it's napping// unfortunately the interrupt() method is not working// if (sleeping)// interrupt();if (suspended) {synchronized(this) {notify();//Diagnostic.out.println("TIMER: Resume");suspended = false;}}}/*** Find the job and mark it for deletion*/public void end(TimerClient client, int eventId) {synchronized (tasks) {for (int i = 0; i < tasks.size(); i++) {TimerTask t = (TimerTask)tasks.elementAt(i);//if (!t.deletePending && t.client == client && t.eventId == eventId)if (t.deletePending == false && t.client == client && t.event Id == eventId) {// JPBS - if we don't reset 'repeat', deletePending will be set againt.repeat = false;t.deletePending = true;break;}}}}/*** Clear out all the dead woodvoid purge() {for (int i = 0; i < tasks.size(); i++) {TimerTask t = (TimerTask)tasks.elementAt(i);if (t.deletePending) {//Diagnostic.out.println("TIMER: purged");tasks.removeElementAt(i);i--;}}}long scan() {// The value added to the current time determines the MAX time un til// the next scan// This is 100 now since thread.interrupt() is not implementedlong nextTime = System.currentTimeMillis() + 100;for (int i = 0; i < tasks.size(); i++) {TimerTask t = (TimerTask)tasks.elementAt(i);// if not already deletePending, test (and possibly send the ev ent)// as a result, the job may be flagged for deletion.// May also be a non-repeating job and so require self deletion if (!t.deletePending)t.test();// if the task didn't get deleted - see what it contributes to the timeif (!t.deletePending)nextTime = Math.min(nextTime, t.timeNext);//Diagnostic.out.println("TIMER: Scanning "+t.eventId+" "+(t.de letePending == true ? "DEL" : ""));return nextTime - System.currentTimeMillis();}}class TimerTask{TimerClient client;int eventId;long timePrev;long timeDelay;long timeNext;boolean repeat;boolean deletePending;public TimerTask(TimerClient client, int eventId, long timeDelay, b oolean repeat) {this.client = client;this.eventId = eventId;this.timeDelay = timeDelay;this.repeat = repeat;// schedule the next click - now + delaytimeNext = System.currentTimeMillis() + timeDelay;deletePending = false;//Diagnostic.out.println("TIMER: Adding New Task");}public void test() {if (System.currentTimeMillis() >= timeNext) {//Diagnostic.out.println("TIMER: fire");// Fire the eventclient.timerEvent(eventId);// Update the next timetimeNext = System.currentTimeMillis() + timeDelay;deletePending = !repeat;}}}下面是使用上面的异步socket类,做的demo开发DemoAppSocketHandler.javapackage ;import .*;import java.util.*;/*** Title:* Description:* Copyright: Copyright (c) 2001* Company: * @author dozb* @version 1.0*/public interface DemoAppSocketHandler{//当客户端sock有数据到达时触发public void OnProcessCmd(Object socket,String FromArea,String ToArea,String ChannNo,String MainFun,String SubFun,Vector ParamLis t);//当客户端sock连接建立成功时触发public void OnConnect(Object socket);//当服务端sock监听开始时触发public void OnListen(Object socket);//当服务端sock接受一个新的sock连接时触发public void OnAccept(Object socket,SocketEx ClientSocket) ;//当sock关闭时触发public void OnClose(Object socket);}DemoAppSocket.javapackage ;import java.io.*;import java.util.*;import com.ly.util.*;/*** Title:* Description:* Copyright: Copyright (c) 2001* Company: * @author dozb* @version 1.0*///这个类是异步socket 客户端和服务端的使用演示//对于客户端,实现了断开后自动连接//这个类是SocketExHandler 和 TimerClient 接口的实现public class DemoAppSocket implements SocketExHandler,TimerClient{//Sock构造函数public DemoAppSocket(DemoAppSocketHandler issh,boolean isServ er,String ip,int port) {this.issh = issh;this.isServer = isServer;this.ip = ip;if(this.ip == null) this.ip = "";this.port = port;if(this.port <0) this.port = 0;}//调用完构造后调用这个函数创建sock对象public void create(){if(!start())TimerCtl.startTimer(this,eventId,30*1000,true);}//这个方法一般不需要直接调用public boolean start(){if(this.isServer) return startServer(); else return s tartClient();}//停止socketpublic void stop(){TimerCtl.stopTimer(this,eventId);if(this.isServer) stopServer(); else stopClient();}//发送socket消息public boolean SendCmd(Object socket,String strCmd){SocketEx currSocketEx = (SocketEx)socket;if(!isServer && currSocketEx==null) currSocketEx = so cketEx;if(currSocketEx == null) return false;try{PrintWriter Sender = new PrintWriter(currSocketEx.getOutp utStream(),true);Sender.print(strCmd);Sender.flush();return true;}catch(Exception e){return false;}}//发送socket消息public boolean SendCmd(Object socket,String FromArea,String ToArea, String ChannNo,String MainFun,String SubFun,String Param){String strCmd = FromArea + ToArea + ChannNo + MainFun+SubFun+ "&"+Param+"&";return SendCmd(socket,strCmd);}//获得IP地址public String getIp(){return ip;}//获得端口号public int getPort(){return port;}protected boolean startClient(){if(socketEx != null) {try{socketEx.close();}catch(IOException e){};socketEx = null;}try{socketEx = new SocketEx(this,ip,port);TimerCtl.stopTimer(this,eventId);return true;}catch(IOException e){socketEx = null;}return false;}protected boolean startServer(){if(serverSocketEx != null) {try{serverSocketEx.close();}catch(IOException e){};serverSocketEx = null;}try{serverSocketEx = new ServerSocketEx(this,port); TimerCtl.stopTimer(this,eventId);return true;}catch(IOException e){serverSocketEx = null;}return false;}protected void stopServer(){if(serverSocketEx != null) {try{serverSocketEx.close();}catch(IOException e){};serverSocketEx = null;}}protected void stopClient(){if(socketEx != null) {try{socketEx.close();}catch(IOException e){};socketEx = null;}}public void timerEvent(int id){start();}static public String[] DealStr(String strS){int CMDHEAD_LEN = 22;String[] ret = new String[2];//0留下的字符串1完整的CMD ret[0]=strS;////假如只有一个&或没有&则不完整int FirstPos=strS.indexOf("&");if(FirstPos==-1)return ret;if(FirstPos != CMDHEAD_LEN-1){strS = strS.substring(FirstPos+1);return DealStr(strS);}int nSecondPos = strS.indexOf("&",FirstPos+1);if(nSecondPos<0)return ret;//可能格式不正确了if(strS.length()< CMDHEAD_LEN)return ret;ret[1] = strS.substring(0,nSecondPos+1);ret[0]=strS.substring(nSecondPos+1);return ret;}public void OnReceive(Object socket,byte buf[],int nLen){String ReceiveBuff = sReceiveBuf + (new String(buf,0,nLen));do//分解成单个的命令串{String strCmd[] = DealStr(ReceiveBuff);ReceiveBuff = strCmd[0];if(strCmd[1]==null || strCmd[1].equals("")) br eak;System.out.println(strCmd[1]);String FromArea=strCmd[1].substring(0,6);String ToArea=strCmd[1].substring(6,12);String ChannNo=strCmd[1].substring(12,15);String MainFun=strCmd[1].substring(15,18);String SubFun=strCmd[1].substring(18,21);String Param =strCmd[1].substring(22,strCmd[1]. length()-1);Vector ParamList=new Vector();int nLastPos=0;while(true){int nPos = Param.indexOf(",",nLastPo s);if(nPos <0){ParamList.add(Param.substring(n LastPos));// System.out.println(Param.substr ing(nLastPos));break;}String sParam = Param.substring(nLastP os,nPos);ParamList.add(sParam);// System.out.println(sParam);nLastPos = nPos+1;}DoProcessCmd(socket,FromArea,ToArea,ChannNo,Ma inFun,SubFun,ParamList);}while(true);sReceiveBuf = ReceiveBuff;if(sReceiveBuf == null) sReceiveBuf=null;}protected void DoProcessCmd(Object socket,String FromArea,String ToArea,String ChannNo,String MainFun,String SubFun,Vector ParamList) {if(issh !=null)issh.OnProcessCmd(socket,FromArea,ToArea,Chann No,MainFun, SubFun, ParamList);}public void OnConnect(Object socket){if(issh !=null) issh.OnConnect(socket);}public void OnListen(Object socket){if(issh !=null) issh.OnListen(socket);}public void OnAccept(Object socket,SocketEx ClientSocket) {if(issh !=null) issh.OnAccept(socket,ClientSocket);}public void OnClose(Object socket){notifyAll();TimerCtl.startTimer(this,eventId,30*1000,true);if(issh !=null) issh.OnClose(socket);}//SocketSocketEx socketEx = null;ServerSocketEx serverSocketEx=null;final int eventId = 1;String sReceiveBuf="";DemoAppSocketHandler issh=null;boolean isServer=false;String ip="127.0.0.1";int port=20000;}通过这种方式,可以高效地使用socket通讯,在异步socket版本没有发布以前,不失是一种解决问题的方法。