Description: Implemented based on the UDP protocol of the Netty 3.9.2 (if you are using a version of 4. X or 5.X, refer to other methods); The logical structure of the program is that the client sends a string of data to the server, which is returned to the client "A". In the game development needs to the UDP packet loss processing, can use the server side return value carries on the correlation processing, in order to determine whether the postback, this aspect concrete did not implement.
Article structure:
One, server-side
1, Udpserver
2, Udpchannelpipelinefactory
3, Udpserverhandler
Second, the client
1, UdpClient
2, Udpclientchannelpipelinefactory
3, Udpclienthandler
Iii. Scangetport get an available port number
One, server-side
1, Udpserver
Initializes a connectionlessbootstrap,setpipelinefactory, binding a port number. Scangetport is a tool class that gets an available port number and the source code is posted on the last side.
PackageCom.ls.udp.server;Importjava.net.InetSocketAddress;Importjava.util.concurrent.Executors;ImportOrg.jboss.netty.bootstrap.ConnectionlessBootstrap;Importorg.jboss.netty.channel.socket.nio.NioDatagramChannelFactory;ImportCom.andy.server.util.ScanGetPort; Public classUdpserver { Public Final intPORT; PublicUdpserver (intPort) {PORT=Port; } PrivateConnectionlessbootstrap Bootstrap; voidstart () {//init the bootstrapbootstrap=NewConnectionlessbootstrap (Newniodatagramchannelfactory (Executors.newcachedthreadpool ())); Bootstrap.setpipelinefactory (Newudpchannelpipelinefactory ()); Bootstrap.bind (Newinetsocketaddress (PORT)); System.out.println ("Server start at:" + ":" +PORT); } Public Static voidMain (string[] args) {/** Get an available port number*/ intport=NewScangetport (). Getpot (8080); NewUdpserver (Port). Start (); } }
2, Udpchannelpipelinefactory
Register a handler
PackageCom.ls.udp.server;ImportOrg.jboss.netty.channel.ChannelPipeline;Importorg.jboss.netty.channel.ChannelPipelineFactory;ImportOrg.jboss.netty.channel.Channels; Public classUdpchannelpipelinefactoryImplementschannelpipelinefactory{/*** Set the Channel pipeline **/@Override PublicChannelpipeline Getpipeline ()throwsException {Channelpipeline pipeline=Channels.pipeline (); Pipeline.addlast ("Handler",NewUdpserverhandler ()); returnpipeline; }}
3, Udpserverhandler
Handler class
PackageCom.ls.udp.server;ImportOrg.jboss.netty.buffer.ChannelBuffer;ImportOrg.jboss.netty.buffer.DynamicChannelBuffer;ImportOrg.jboss.netty.channel.ChannelHandlerContext;Importorg.jboss.netty.channel.ExceptionEvent;Importorg.jboss.netty.channel.MessageEvent;ImportOrg.jboss.netty.channel.SimpleChannelUpstreamHandler; Public classUdpserverhandlerextendssimplechannelupstreamhandler{/*** for Channelhandler, * is the core of the difference between UDP and TCP. * Everyone knows that UDP is not connected, * That means you get the current session connection through the Getchannel () method of the Messageevent parameter object, * but its isconnected () always returns false. * UDP development in the message get event callback method, * Gets the current session connection channel object can be directly through the channel write method to send data to the peer Channel.write (message, remoteaddress), * The first parameter is still the message object to be sent, and the second parameter is the peer SocketAddress address object to send. * The most important thing to note here is socketaddress, which we can get through channel.getremoteaddress () in TCP communication, * but in UDP communication, We must obtain the socketaddress address of the peer from the messageevent by calling the Getremoteaddress () method. */@Override Public voidmessagereceived (Channelhandlercontext ctx, messageevent e)throwsException {channelbuffer buffer=(Channelbuffer) e.getmessage (); byte[] recbyte=buffer.copy (). Tobytebuffer (). Array (); String msg=NewString (RecByte); System.out.println ("From client:" +msg); Channelbuffer Responsebuffer=NewDynamicchannelbuffer (1); Responsebuffer.writebytes (A. GetBytes ()); //write to the clientE.getchannel (). Write (Responsebuffer, e.getremoteaddress ()); Super. messagereceived (CTX, E); } @Override Public voidexceptioncaught (Channelhandlercontext ctx, exceptionevent e)throwsException {Super. Exceptioncaught (CTX, E); }}
Second, the client
(Basic structure and server-side very much like, no longer repeat)
1, UdpClient
Packagecom.ls.udp.client;Importjava.net.InetSocketAddress;ImportJava.util.Scanner;ImportOrg.jboss.netty.bootstrap.ConnectionlessBootstrap;ImportOrg.jboss.netty.buffer.ChannelBuffer;ImportOrg.jboss.netty.buffer.DynamicChannelBuffer;ImportOrg.jboss.netty.channel.Channel;Importorg.jboss.netty.channel.socket.nio.NioDatagramChannelFactory; Public classUdpClient {PrivateConnectionlessbootstrap Bootstrap; Privatechannel Channel; Public voidstart () {//init the bootstrapbootstrap=NewConnectionlessbootstrap (Newniodatagramchannelfactory ()); Bootstrap.setpipelinefactory (Newudpclientchannelpipelinefactory ()); Bootstrap.setoption ("LocalAddress",NewInetsocketaddress (10001)); Channel=Bootstrap.bind (); } Public voidWritebytes (byte[] Bt,inetsocketaddress ISA) { if(bootstrap==NULL){ This. Start (); } channelbuffer Responsebuffer=NewDynamicchannelbuffer (12); Responsebuffer.writebytes (BT); Channel.write (Responsebuffer, ISA); } Public Static voidMain (string[] args) {udpclient uclient=NewUdpClient (); Scanner Scanner=NewScanner (system.in); String lienstring=Scanner.nextline (); while(!lienstring.equals ("Bye") {uclient.writebytes (Lienstring.getbytes ()),NewInetsocketaddress ("192.168.1.107", 8080)); Lienstring=Scanner.nextline (); } } }
2, Udpclientchannelpipelinefactory
Packagecom.ls.udp.client;ImportOrg.jboss.netty.channel.ChannelPipeline;Importorg.jboss.netty.channel.ChannelPipelineFactory;ImportOrg.jboss.netty.channel.Channels; Public classUdpclientchannelpipelinefactoryImplementschannelpipelinefactory{/*** Set the Channel pipeline **/@Override PublicChannelpipeline Getpipeline ()throwsException {Channelpipeline pipeline=Channels.pipeline (); Pipeline.addlast ("Handler",NewUdpclienthandler ()); returnpipeline; }}
3, Udpclienthandler
Packagecom.ls.udp.client;ImportOrg.jboss.netty.buffer.ChannelBuffer;ImportOrg.jboss.netty.channel.ChannelHandlerContext;Importorg.jboss.netty.channel.ExceptionEvent;Importorg.jboss.netty.channel.MessageEvent;ImportOrg.jboss.netty.channel.SimpleChannelUpstreamHandler; Public classUdpclienthandlerextendssimplechannelupstreamhandler{@Override Public voidmessagereceived (Channelhandlercontext ctx, messageevent e)throwsException {channelbuffer buffer=(Channelbuffer) e.getmessage (); byte[] recbyte=buffer.copy (). Tobytebuffer (). Array (); String msg=NewString (RecByte); System.out.println ("From server:" +msg); Super. messagereceived (CTX, E); } @Override Public voidexceptioncaught (Channelhandlercontext ctx, exceptionevent e)throwsException {Super. Exceptioncaught (CTX, E); } }
Iii. Scangetport get an available port number
PackageCom.andy.server.util;Importjava.io.IOException;ImportJava.net.ServerSocket;/*** Get the port *@authorRed **/ Public classScangetport { Public synchronized intGetpot (intFirst ) { for(inti=first;i<65535;++i) {ServerSocket SS=NULL; Try{SS=NewServerSocket (i); } Catch(IOException e) {//e.printstacktrace ();}finally{ if(ss!=NULL){ if(Ss.isbound ()) {Try{ss.close (); System.out.println (i); returni; } Catch(IOException e) {e.printstacktrace (); } } } } } return-1; }}