【2013-12-16】《Java编程思想》读书笔记:UDP

发布时间:2026/7/15 19:54:58
【2013-12-16】《Java编程思想》读书笔记:UDP [历史归档]本文原发布于 cstriker1407.info 个人博客内容为历史存档仅供参考。发布时间2013-12-16 标题《Java编程思想》读书笔记:UDP分类编程 / java 标签java·UDP《Java编程思想》读书笔记UDP最近用到了UDP实现一个小功能就找了下UDP的实现代码这里备份下简单的实现。备注UDP的业务很简单知道了对方的IP和端口号无需建立连接就可以发送数据。publicclassUDPTools{publicstaticfinalUDPToolsInstancenewUDPTools();privateUDPTools(){}publicstaticinterfaceonRevUDPDataController{publicvoidonRevUDPData(byte[]data,intoffset,intlength);}privateintlocalSvrPort60000;privateintremotePort50000;privateDatagramSocketclientnull;privateDatagramSocketservernull;privateonRevUDPDataController controller;privateStringremoteIP;privatevolatilebooleanisReadingtrue;publicbooleandeinit(){if(client!null){client.close();}if(server!null){server.close();}clientnull;servernull;returntrue;}publicbooleaninit(onRevUDPDataController controller,intlocalSvrPort,intremotePort,StringremoteIP){if(client!null){returnfalse;}if(nullcontroller||localSvrPort1024||remotePort1024||localSvrPort65535||remotePort65535||nullremoteIP||remoteIP.length()192.168.168.168.length()){returnfalse;}this.controllercontroller;this.localSvrPortlocalSvrPort;this.remotePortremotePort;this.remoteIPnewString(remoteIP);try{clientnewDatagramSocket();servernewDatagramSocket(this.localSvrPort);isReadingtrue;}catch(SocketExceptione){e.printStackTrace();if(client!null){client.close();}if(server!null){server.close();}clientnull;servernull;returnfalse;}returntrue;}publicbooleansendToSvr(byte[]data,intoffset,intlength){if(client!null){DatagramPacketpack;try{packnewDatagramPacket(data,offset,length,InetAddress.getByName(remoteIP),remotePort);client.send(pack);}catch(UnknownHostExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}else{returnfalse;}returntrue;}publicbooleanstopReadFromRemote(){isReadingfalse;returntrue;}publicbooleanbeginReadFromRemote(){try{while(isReading){byte[]messagenewbyte[1024];DatagramPacketpacketnewDatagramPacket(message,message.length);server.receive(packet);controller.onRevUDPData(packet.getData(),packet.getOffset(),packet.getLength());}returntrue;}catch(IOExceptione){e.printStackTrace();// controller.onRevUDPData(null, 0, 0);returnfalse;}}}