NIO Socket 简单通信实例

本文介绍了一个简单的非阻塞I/O(NIO)服务端和客户端实现案例。服务端监听客户端连接请求,并向客户端发送欢迎消息;客户端连接服务端并接收其返回的消息。该示例使用了Java NIO中的Selector、ServerSocketChannel和SocketChannel等核心组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里只是保存一下,功能还会继续完善。

目前的功能为

服务端:接收客户端的请求并返回一个字符串给客户端

客户端:连接到服务器,并读取服务端返回的数据


服务端:

package com.zf.test02;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
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;

public class SelectorServer {

	private Selector selector  ;

	private ServerSocketChannel serverChannel ;

	private ByteBuffer buff ;

	public SelectorServer(){
		try {
			selector = Selector.open() ;
			serverChannel = ServerSocketChannel.open() ;
			serverChannel.configureBlocking(false) ;
			serverChannel.socket().bind(new InetSocketAddress(8888));
			serverChannel.register(selector, SelectionKey.OP_ACCEPT) ;
			buff = ByteBuffer.allocate(1024) ;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void openServer() throws IOException{

		while(true){
			System.out.println("正在select等待下一步操作...");
			int keys = selector.select() ;
			if(keys > 0){
				Iterator<SelectionKey> itKeys = selector.selectedKeys().iterator() ;
				while(itKeys.hasNext()){
					SelectionKey key = itKeys.next() ;
					if(key.isAcceptable()){
						System.out.println("发现有客户端加入,Accept方法激活...");
						ServerSocketChannel ss = (ServerSocketChannel)key.channel();
						SocketChannel clientChannel = ss.accept();
						System.out.println("接收到来自" + clientChannel.socket().getRemoteSocketAddress() + "的请求");
						writeMessageToClient(clientChannel , "Hello Welcome!");
						System.out.println("向客户端" + clientChannel.socket().getRemoteSocketAddress() + "发送信息成功");
					}
					itKeys.remove();
				}

			}

		}





	}

	public void writeMessageToClient(SocketChannel clientChannel , String message){
		try {
			buff.clear() ;
			buff.put(message.getBytes("UTF-8"))  ;
			buff.flip() ;  
			clientChannel.write(buff) ;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws IOException {

		SelectorServer ss = new SelectorServer() ;

		ss.openServer(); 

	}

}

客户端:

package com.zf.test02;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class SelectorClient {

	private SocketChannel socketChannel ;
	private InetSocketAddress serverAddress;
	private Selector selector  ;
	private ByteBuffer buf = ByteBuffer.allocate(1024) ;

	public SelectorClient(){
		try {
			serverAddress = new
					InetSocketAddress(InetAddress.getByName("127.0.0.1"), 8888) ;
			socketChannel = SocketChannel.open(serverAddress) ;
			socketChannel.configureBlocking(false);
			selector = Selector.open() ;
			socketChannel.register(selector, 
					SelectionKey.OP_READ) ;
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void connectServer() throws IOException{  
		while(true	){
			int keys = selector.select() ;
			System.out.println("检测到动态...");
			if(keys > 0){
				Iterator<SelectionKey> itKeys =    
						selector.selectedKeys().iterator() ;
				while(itKeys.hasNext()){

					SelectionKey key = itKeys.next() ;

					if(key.isReadable()){
						readMessageFromChannel() ;
					}
					itKeys.remove();
				}
			}
		}

	}

	public void readMessageFromChannel() throws IOException{
		buf.clear() ;
		socketChannel.read(buf) ;
		buf.flip();
		System.out.println("服务端返回数据:" + new String(buf.array() ,
				0 , buf.limit() , "UTF-8"));  
	}

	public static void main(String[] args) throws IOException {

		SelectorClient client = new SelectorClient();
		client.connectServer(); 


	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值