当前位置: 首页 > 工具软件 > Naga > 使用案例 >

Naga编程的实例应用

马淇
2023-12-01

       Naga是一个非常小的NIO类库。提供封装Socket和ServerSocket的几个Java类。

简单的类介绍如下:

 

NIOService :创建NIO流的服务对象

NIOServerSocket :相当于IO中ServerSocket

NIOSocket 相当于IO中Socket

ServerSocketObserverAdapter:服务器端ServerSocket的监听适配器

SocketObserverAdapter:客户端SOcket器端的监听适配器

 

 

服务端代码如下:

package com.easyway.space.sockets.naga;

import naga.*;
import naga.packetreader.RegularPacketReader;
import naga.packetwriter.RegularPacketWriter;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 远程请求服务验证的服务端
 * @author longgangbai
 *
 */
public class NagaServer
{
	NagaServer() {
	}

	public static void main(String... args)
	{
		int port =8090;
		// Create a map with users and passwords.
		//创建一个Map用于存储关于用户的信息的
		final Map<String, String> passwords = new HashMap<String, String>();
		passwords.put("Admin", "password");
		passwords.put("Aaron", "AAAAAAAA");
		passwords.put("Bob", "QWERTY");
		passwords.put("Lisa", "secret");
		try
		{
			//创建一个NIOService服务对象
			NIOService service = new NIOService();
			//创建一个NIOServerSocket服务端对象
			NIOServerSocket socket = service.openServerSocket(port);
			//服务端添加相关的监听器
			socket.listen(new ServerSocketObserverAdapter()
			{
				//当连接成功时执行的代码
				public void newConnection(NIOSocket nioSocket)
				{
					System.out.println("Received connection: " + nioSocket);

					// Set a 1 byte header regular reader.
					nioSocket.setPacketReader(new RegularPacketReader(1, true));

					// Set a 1 byte header regular writer.
					nioSocket.setPacketWriter(new RegularPacketWriter(1, true));

					// Listen on the connection.
					//监听到Socket信息是处理方式
					//备注此处采用的是Socket的观察者适配器
					nioSocket.listen(new SocketObserverAdapter()
					{
						/**
						 * 写数据的到客户端
						 * @param socket
						 * @param packet
						 */
						@SuppressWarnings("unused")
						public void notifyReadPacket(NIOSocket socket, byte[] packet)   
						{     
							socket.write(packet);   
						} 
						/**
						 * 连接发生异常时的处理
						 */
						public void connectionBroken(NIOSocket nioSocket, Exception exception)
						{
						}

                        /**
                         * 连接打开时执行的操作
                         */
						public void connectionOpened(NIOSocket nioSocket)
						{
						}
						/**
						 * 接受数据包的信息
						 */
						public void packetReceived(NIOSocket socket, byte[] packet)
						{
							// We received a packet. Should contain two encoded
							// UTF strings with user and password.
							System.out.println("Login attempt from " + socket);
							try
							{
								// Let us unpack the bytes by converting the bytes to a stream.
								//获取输入的信息
								DataInputStream stream = new DataInputStream(new ByteArrayInputStream(packet));

								// Read the two strings.
								//获取相关的信息
								String user = stream.readUTF();
								String password = stream.readUTF();

								// Prepare to encode the response.
								ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
								DataOutputStream out = new DataOutputStream(byteArrayOutputStream);

								if (!passwords.containsKey(user))
								{
									System.out.println("Unknown user: " + user);
									out.writeUTF("NO_SUCH_USER");
								}
								else if (!passwords.get(user).equals(password))
								{
									out.writeUTF("INCORRECT_PASS");
									System.out.println("Failed login for: " + user);
								}
								else
								{
									out.writeUTF("LOGIN_OK");
									System.out.println("Successful login for: " + user);
								}

								// Create the outgoing packet.
								out.flush();
								//写数据到客户端
								socket.write(byteArrayOutputStream.toByteArray());

								// Close after the packet has finished writing.
								//关闭当前写入流
								socket.closeAfterWrite();
							}
							catch (IOException e)
							{
								// No error handling to speak of.
								//关闭当前的连接
								socket.close();
							}
						}
					});
				}
			});
			
			// Allow all logins.
			//允许所有的不同的ip连接服务器
			socket.setConnectionAcceptor(ConnectionAcceptor.ALLOW);

			// Keep reading IO forever.
			//保持服务为阻塞状态的信息
			while (true)
			{
				service.selectBlocking();
			}
		}
		catch (IOException e)
		{
		}
	}


}

 

 

 

客户端代码如下:

package com.easyway.space.sockets.naga;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;

import naga.NIOService;
import naga.NIOSocket;
import naga.SocketObserver;
import naga.SocketObserverAdapter;
import naga.packetreader.RegularPacketReader;
import naga.packetwriter.RegularPacketWriter;

/**
 * Naga的远程客户端验证 的客户端的代码
 * @author longgangbai
 *
 */
public class NagaClient
{
	NagaClient()
	{}

	/**
	 * Make a login request to the server.
	 *
	 * @param args assumed to be 4 strings representing host, port, account and password.
	 */
	public static void main(String... args)
	{
		try
		{
			// Parse arguments.
			String hostName = "localhost";
			int port = 8090;
			//设置登录的账号信息
			String account ="Admin";
			String password = "password";

			// Prepare the login packet, packing two UTF strings together
			// using a data output stream.
			//将信息写入流中发送到服务端
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			DataOutputStream dataStream = new DataOutputStream(stream);
			dataStream.writeUTF(account);
			dataStream.writeUTF(password);
			dataStream.flush();
			final byte[] content = stream.toByteArray();
			dataStream.close();

			// Start up the service.
			//设置NIOService的服务对象
			NIOService service = new NIOService();

			//获取相关的ip的信息
			InetAddress intaddress=InetAddress.getByName(hostName);
			// Open our socket.
			//打开当前请求的Socket的对象
			NIOSocket socket = service.openSocket(intaddress.getHostAddress(), port);

			// Use regular 1 byte header reader/writer
			//设置读写信息包的信息
			socket.setPacketReader(new RegularPacketReader(1, true));
			socket.setPacketWriter(new RegularPacketWriter(1, true));

			// Start listening to the socket.
			//添加相关的监听事件用于监听客户端
			socket.listen(new SocketObserver()
			{
				/** A null object used as the default observer */
				SocketObserver NULL = new SocketObserverAdapter();
				/**
				 * 连接成功时的相关的操作
				 */
				public void connectionOpened(NIOSocket nioSocket)
				{
					System.out.println("Sending login...");
					nioSocket.write(content);
				}
                //用于接收服务端的信息
				public void packetReceived(NIOSocket socket, byte[] packet)
				{
					try
					{
						// Read the UTF-reply and print it.
						String reply = new DataInputStream(new ByteArrayInputStream(packet)).readUTF();
						System.out.println("Reply was: " + reply);
						// Exit the program.
						System.exit(0);
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
                //用于接受服务端连接发生异常时的处理方式
				public void connectionBroken(NIOSocket nioSocket, Exception exception)
				{
					System.out.println("Connection failed.");
					// Exit the program.
					System.exit(-1);
				}
			});
			// Read IO until process exits.
			//采用阻塞式读取IO信息,知道进程退出
			while (true)
			{
				service.selectBlocking();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

}

 

 

 

代码如上有不解,希望大家可以沟通,谢谢!

 类似资料: