java NIO serversocket

纯自用

server端:


import java.io.ByteArrayOutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.HexUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SGServer {

	public static void main(String[] args) {
		SGServer server = new SGServer();
		server.run();
	}

	private int port = 8080;
	private ServerSocketChannel ssc = null;
	private Selector selector = null;

	public void init() throws Exception {
		if (null == ssc) {
			ssc = ServerSocketChannel.open();
			ssc.socket().bind(new InetSocketAddress(port));
			ssc.configureBlocking(false);
			selector = Selector.open();
			ssc.register(selector, SelectionKey.OP_ACCEPT);
		}
	}

	public void run() {
		SelectionKey key = null;
		try {
			this.init();

			while (true) {
				if (selector.select(3000) == 0) {
					continue;
				}
				Set<SelectionKey> selectionKeys = selector.selectedKeys();
				Iterator<SelectionKey> iter = selectionKeys.iterator();
				while (iter.hasNext()) {
					key = iter.next();
					iter.remove();

					if (key.isValid() && key.isAcceptable()) {
						SocketChannel sc = ssc.accept();
						sc.configureBlocking(false);
						System.out.println("有一个客户端连接成功,hashCode = " + sc.hashCode());
						sc.register(selector, SelectionKey.OP_READ);
					}
					if (key.isValid() && key.isReadable()) {
						SocketChannel sc = (SocketChannel) key.channel();
						ByteBuffer buff = ByteBuffer.allocate(1024);
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						while (sc.read(buff) > 0) {
							int pos = buff.position();
							if (pos < buff.capacity()) {
								baos.write(ArrayUtil.sub(buff.array(), 0, pos));
							} else {
								baos.write(buff.array());
							}
						}
						String hex = HexUtil.encodeHexStr(baos.toByteArray());
						System.out.println("客户端发送:" + hex);

						// TODO 其他业务处理,并返回data
						byte[] data = {};

						data = "qwertyuiopasdfghjklzxcvbnm".getBytes();
						sc.register(selector, SelectionKey.OP_WRITE);
						key.attach(ByteBuffer.wrap(data));
					}
					if (key.isValid() && key.isWritable()) {
						SocketChannel sc = (SocketChannel) key.channel();
						ByteBuffer buff = (ByteBuffer) key.attachment();
						if (null != buff) {
							sc.write(buff);
						}
						sc.close();
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
		}

	}

}

client端:


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.HexUtil;

public class SGClient {

	public static void main(String[] args) {
		SGClient client = new SGClient();
		byte[] msg = "1234567890abcdef1234567890abcdef".getBytes();
		client.sendMsg(msg);
	}

	private String host = "127.0.0.1";
	private int port = 8080;

	public void sendMsg(byte[] msg) {
		// 1、创建客户端Socket,指定服务器地址和端口
		try {
			Socket socket = new Socket("localhost", 10020);
			// 2、获取输出流,向服务器端发送信息
			OutputStream os = socket.getOutputStream();// 获取字节输出流

			String str = "https://www.jit.com.cn";
			os.write(str.getBytes("UTF-8"));

			byte[] buff = new byte[1024];
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			InputStream is = socket.getInputStream();
			int pos = 0;
			while ((pos = is.read(buff)) > 0) {
				if (pos < buff.length) {
					baos.write(ArrayUtil.sub(buff, 0, pos));
				} else {
					baos.write(buff);
				}
			}
			String hex = HexUtil.encodeHexStr(baos.toByteArray());
			System.out.println("服务返回:" + hex);

			// 3、关闭资源
			os.close();
			socket.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void sendMsg1(byte[] msg) {
		SocketChannel sc = null;
		try {
			sc = SocketChannel.open();
			sc.connect(new InetSocketAddress(host, port));
			sc.configureBlocking(true);
			sc.write(ByteBuffer.wrap(msg));

			ByteBuffer buff = ByteBuffer.allocate(1024);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while (sc.read(buff) > 0) {
				byte[] data = buff.array();
				int pos = buff.position();
				if (pos < buff.capacity()) {
					data = ArrayUtil.sub(data, 0, pos);
				}
				baos.write(data);
			}
			String hex = HexUtil.encodeHexStr(baos.toByteArray());
			System.out.println("服务返回:" + hex);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != sc) {
				try {
					sc.close();
					sc = null;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	
	
	
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值