Netty服务器Demo

代码在我自己的gitlab:

http://120.76.219.142/marc/nettyServer

DML类:

package com.wulala;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;
import java.util.UUID;

public class ExecuteDML {
	private String driver;
	private String url;
	private String user;
	private String password;

	public void initParam(String paramFile) throws Exception {
		Properties props = new Properties();
		props.load(new FileInputStream(paramFile));
		driver = props.getProperty("driverClassName");
		url = props.getProperty("url");
		user = props.getProperty("user");
		password = props.getProperty("password");

	}

	public int insertData(String data) throws Exception {
		Class.forName(driver);
		try (Connection conn = DriverManager.getConnection(url, user, password);
				Statement stmt = conn.createStatement()) {
			return stmt.executeUpdate("INSERT INTO MEMS_REC (ID,X,Y, CREATE_TIME) VALUES ('"
					+ UUID.randomUUID().toString() + "','1','" + data + "', now());");
		}
	}

	public int insertWXData(String deviceID, int activate) throws Exception {
		Class.forName(driver);
		try (Connection conn = DriverManager.getConnection(url, user, password);
				Statement stmt = conn.createStatement()) {
			return stmt.executeUpdate("INSERT INTO WANG_XIN (ID,DEVICE_ID,ACTIVATE) VALUES ('"
					+ UUID.randomUUID().toString() + "','" + deviceID + "'," + activate + ");");
		}
	}

	/*public static void main(String[] args) {

		ExecuteDML edml = new ExecuteDML();
		int result=0;
		try {
			edml.initParam("dbconfig.properties");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			result = edml.insertWXData("xxxxasdf", 9999);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Total " + result + " record been add");
	}
*/
}

 

Handler类:

package com.wulala;

import java.io.UnsupportedEncodingException;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class TimeServerHandler extends ChannelHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = "";
		try {
			body = new String(req, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (body.length() > 8 && (body.length() < 15)) {
			System.out.println("The time server receive order: " + body);
			ExecuteDML edml = new ExecuteDML();
			String deviceID = body.substring(0, 8);
			int activate = Integer.valueOf(body.substring(8));
			int insertResult = 0;
			System.out.println("devceiID: " + deviceID + " activate: " + activate);
			try {
				edml.initParam("dbconfig.properties");
				insertResult = edml.insertWXData(deviceID, activate);
				// insertResult = edml.insertWXData("xxxxasdf", 1234);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("Total " + insertResult + " result been changed");
		}
		// String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new
		// java.util.Date(System.currentTimeMillis()).toString() : "BAD ORDER";
		// ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		// ctx.write(resp);

	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		ctx.close();

	}

}

 

MainServer类:

package com.wulala;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TimeServer {
	public void bind(int port) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024)
					.childHandler(new ChildChannelHandler());
			ChannelFuture f = b.bind(port).sync();
			f.channel().closeFuture().sync();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();

		}

	}

	private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
		@Override
		protected void initChannel(SocketChannel arg0) throws Exception {
			arg0.pipeline().addLast(new TimeServerHandler());
		}

	}

	public static void main(String[] args) throws Exception {
		int port = 9998;
		new TimeServer().bind(port); 

	}
}

 

Client类:

package com.wulala;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	public static void main(String[] args) throws InterruptedException {
		for (int i = 1; i < 10; i++) {
			SocketClient socketClient = new SocketClient();
			socketClient.i = i;
			socketClient.start();
		}

		// while (true) {

		// Client client = new Client();
		// client.run();
		// Thread.sleep(1000);
		// }

	}

	public void run() {
		Socket client;
		try {
			// client = new Socket("127.0.0.1", 9998);
			client = new Socket("120.25.76.67", 9998);
			// 2.鎵撳紑socket鐨勬祦淇℃伅锛屽噯澶囦笅闈㈢殑鎿嶄綔
			OutputStream os = client.getOutputStream();

			// 3.鍐欎俊鎭�
			os.write(("xxxxasdf123456").getBytes());

			// for (int i = 0; i < 1000000; i++) {
			//
			// System.out.println("waiting...");
			// }
			os.flush();
			os.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

class SocketClient extends Thread {

	int i;

	@Override
	public void run() {

		// 1.寤虹珛scoket杩炴帴
		Socket client;
		try {
			client = new Socket("120.25.76.67", 9998);

			// 2.鎵撳紑socket鐨勬祦淇℃伅锛屽噯澶囦笅闈㈢殑鎿嶄綔
			OutputStream os = client.getOutputStream();

			// 3.鍐欎俊鎭�
			os.write(("xxxxasdf" + Thread.currentThread().getId()).getBytes());

			// String filmName = "c://io" + i + ".rmvb";
			//
			// FileOutputStream fileOutputStream = new
			// FileOutputStream(filmName);
			//
			// // 3.1鎺ユ敹鏈嶅姟鍣ㄧ鐨勫弽棣�
			// InputStream is = client.getInputStream();
			// byte b[] = new byte[1024];
			//
			// while (is.read(b) > 0) {
			// fileOutputStream.write(b);
			// }

			// 4.鍏抽棴socket
			// 鍏堝叧闂緭鍑烘祦
			os.flush();
			os.close();

			// 鏈�鍚庡叧闂璼ocket
			client.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

 

 

具体实现就是Netty负责驱动一个DML的类, 往数据库里面填入一个值.

仅此而已.

 

测试过并发(100线程个同时访问.)

https://app01.saferkid.net/IntelGeek/record/getLast20DeviceRecordByCustomerId.do

访问这个接口可以看到效果.

这个接口接下来可能会移植到一个静态的网站中去.

 

posted @ 2017-02-27 16:36  Montauk  阅读(254)  评论(0编辑  收藏  举报