java中异步socket类的实现和源代码精品资料.doc

上传人:封****n 文档编号:96698342 上传时间:2024-03-10 格式:DOC 页数:48 大小:320KB
返回 下载 相关 举报
java中异步socket类的实现和源代码精品资料.doc_第1页
第1页 / 共48页
java中异步socket类的实现和源代码精品资料.doc_第2页
第2页 / 共48页
点击查看更多>>
资源描述

《java中异步socket类的实现和源代码精品资料.doc》由会员分享,可在线阅读,更多相关《java中异步socket类的实现和源代码精品资料.doc(48页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、【java编程】java中异步socket类的实现和源代码- - java中异步socket类的实现和源代码作者:dozb我们知道,java中socket类一般操作都是同步进行,常常在read的时候socket就会阻塞直到有数据可读或socket连接断开的时候才返回,虽然可以设置超时返回,但是这样比较低效,需要做一个循环来不停扫描数据是否可读。看来,在同一个线程中,要是想实现异步读写不太容易。下面介绍的这个类实现了伪异步socket通讯。基本思想就是在现有socket类的基础上进行封装,当socket连接建立成功后,立即创建一个socket数据接收线程,专门负责阻塞式的socket读取(rea

2、d),而当前线程负责数据的发送(send)。另外定义了一个接口,包括了socket的各种事件的回调。我们要实现这个接口,在接口实现类中创建异步socket对象,并且传递接口类到异步socket对象中,目的是有socket事件的时候回调我们的方法。下面是接口:SocketExHandler.java package ;import .*; /* * Title: * Description: * Copyright: Copyright (c) 2001 * Company: * author dozb * version 1.0 */* * 异步Socket Client Interface

3、* 使用方法: * 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 * 使用方法

4、: * 1.定义类 MySocketServerEx 实现SocketExHandler接口,实现 OnReceive OnListen OnClose OnAccept 事件 * 2.在类中实现start方法 MySocketEx = new ServerSocketEx(this,ip,port) * 3.在类中实现stop方法 delete MySocketEx * 4.当开始监听时会触发OnListen事件 * 5.当SOCKET关闭时会触发OnClose事件 * 6.当有客户端SOCKET要建立连接时会触发OnAccept事件 */public interface SocketExH

5、andler/当客户端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(Ob

6、ject socket); 下面是异步客户端socket类: SocketEx.java package ;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 Runnablepublic static final boolean isdebug

7、 = true;/调试/* *构造函数. */public SocketEx(SocketExHandler seh,Socket ClientSocket)this.seh = seh;thisSocket = ClientSocket;InitNotify();public SocketEx(SocketExHandler seh,String host,int port) throws IOException this.seh = seh;thisSocket = new Socket(host,port);InitNotify();public SocketEx(SocketExHan

8、dler seh, InetAddress address, int port ) throws IOException this.seh = seh;thisSocket = new Socket(address, port);InitNotify();public SocketEx(SocketExHandler seh, String host, int port, InetAddress localAddr, int localPort ) throws IOException this.seh = seh;thisSocket = new Socket(host,port,local

9、Addr,localPort );InitNotify();public SocketEx(SocketExHandler seh, InetAddress address, int port, InetAddress localAddr, int localPort ) throws IOException this.seh = seh;thisSocket = new Socket(address, port, localAddr,localPort );InitNotify();/* * 实现Socket的可见方法. */public synchronized void close()

10、throws IOExceptionIsRunning = false;thisSocket.close();public InetAddress getInetAddress() return thisSocket.getInetAddress();public InputStream getInputStream() throws IOExceptionreturn thisSocket.getInputStream(); public InetAddress getLocalAddress() return thisSocket.getLocalAddress() ; public in

11、t getLocalPort() return thisSocket.getLocalPort() ; public OutputStream getOutputStream() throws IOExceptionreturn thisSocket.getOutputStream(); public int getPort() return thisSocket.getPort() ; public int getSoLinger() throws SocketExceptionreturn thisSocket.getSoLinger(); public synchronized int

12、getSoTimeout() throws SocketException return thisSocket.getSoTimeout(); public boolean getTcpNoDelay() throws SocketException return thisSocket.getTcpNoDelay(); public void setSoLinger( boolean on, int val ) throws SocketException thisSocket.setSoLinger(on,val); public synchronized void setSoTimeout

13、( int timeout ) throws SocketException thisSocket.setSoTimeout( timeout ) ; public void setTcpNoDelay( boolean on ) throws SocketException thisSocket.setTcpNoDelay(on); public String toString() return thisSocket.toString() ; /* * 获取Socket */public Socket GetSocket()return thisSocket;/* * 初始化异步Socket

14、 */private void ShowMsg(String Msg)if(isdebug)System.out.println(Msg);private void InitNotify()if(NotifyThread != null) return ;trybiStream = new BufferedInputStream(getInputStream();thisSocket.setSoTimeout(0); catch(IOException e)ShowMsg(InitNotify() IOException.);IsRunning = true;NotifyThread = ne

15、w Thread(this,SocketEx_NoitfyThread);NotifyThread.setDaemon(true);NotifyThread.start();if(seh !=null)seh.OnConnect(this);/* * 关闭Socket */private void Close()tryclose();catch(Exception eclose)ShowMsg(Close() Exception.);protected void finalize() throws ThrowableClose();super.finalize();/* * Thread 运行

16、 */public void run()while(IsRunning)tryif(getInputStream().read(buf,0,1) = 0)/试读一个字节DoClose();return ;if(!DoReceive(getInputStream().available()return ;catch(Exception e)ShowMsg(run() Exception.);DoClose();return ;tryThread.sleep(0); /catch(InterruptedException e)ShowMsg(run() InterruptedException.)

17、;DoClose();return ;/* * 当有数据到达时的回调方法. */private boolean DoReceive(int nCanReadCount)tryint len = 0,nCurrReadCount=0,nStart=1;dofor(int i=nStart;i(BUFLEN-2)nCurrReadCount = BUFLEN-2;elsenCurrReadCount = nCanReadCount;len = biStream.read(buf,nStart,nCurrReadCount);if(len = 0)DoClose();return false;nCa

18、nReadCount -= len;buflen+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);/* * 当

19、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

20、final int BUFLEN = 4097;privatebyte buf = new byteBUFLEN;privateBufferedInputStream biStream = null;privateSocketExHandler seh=null; 下面是异步socketserver类: ServerSocketEx .java package ;import java.io.*;import .*; import java.util.*; /* * Title: * Description: * Copyright: Copyright (c) 2001 * Company:

21、 * 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 backlog ) throws I

22、OException super(port,backlog);this.seh = seh;Listen();public ServerSocketEx(SocketExHandler seh, int port, int backlog, InetAddress bindAddr ) throws IOException super(port,backlog, bindAddr);this.seh = seh;Listen();public void setTimeout(int timeout) this.timeout = timeout; public static Vector Ge

23、tClientPool()return ClientPool;public static void CloseAllClients()for(int i=0;i= 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, boolean repeat) TimerTask t = new TimerTask(client, eventId, delay, repeat); synchronized (tasks) tasks.addElement(Object)t); / Want instant response - wake the thread if its napping / unfortunately the interrupt() method is not working/ if (sleeping)/ interrupt(); if (suspended) synchroniz

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 期刊短文 > 互联网

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁