欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

nio 在线聊天 javanio聊天 

程序员文章站 2022-05-28 13:20:10
...

最近在看java nio,模仿别人写了一个,用于学习研究下。没有操作页面,每个客户端另起一个线程来接收消息,client3发送消息时,其他的客户端都能接收到消息

1、服务端

public class ChatService {

	private Selector selector;
	private Charset charset = Charset.forName("UTF-8");
	private SelectionKey service = null;
	private boolean ISRUN = true;
	
	public ChatService() {
		try {
			selector = Selector.open();
			ServerSocketChannel ssc = ServerSocketChannel.open();
			SocketAddress sa = new InetSocketAddress(9999);
			ssc.socket().bind(sa);
			ssc.configureBlocking(false);
			service = ssc.register(selector, SelectionKey.OP_ACCEPT);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void service() {
		try {
			while(ISRUN) {
				if(selector.select()>0) {
					Set<SelectionKey> kes = selector.selectedKeys();
					Iterator<SelectionKey> iter = kes.iterator();
					while(iter.hasNext()) {
						SelectionKey sk = iter.next();
						
						if(sk.isValid() && sk.isAcceptable()) {
							iter.remove(); 
							acceptable(sk);
						}
						if(sk.isValid() && sk.isReadable()) {
							readable(sk);
						}
						if(sk.isValid() && sk.isWritable()) {
							writable(sk);
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void acceptable(SelectionKey key) {
		ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
		try {
			SocketChannel sc = ssc.accept();
			if(sc==null) {
				return ;
			}
			sc.configureBlocking(false);
			sc.register(selector, SelectionKey.OP_READ);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void readable(SelectionKey key) {
		SocketChannel sc = (SocketChannel)key.channel();
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		
		try {
			int num = sc.read(buffer);
			if(num > 0) {
				buffer.flip();
				//CharBuffer cb = buffer.asCharBuffer();
				String request = charset.decode(buffer).toString();
				
				SocketAddress sa = sc.getRemoteAddress();
				System.out.println("客户端信息:"+sa.toString());
				System.out.println("服务端接收信息:"+request);
				
				Set<SelectionKey> keys = selector.selectedKeys();
				Iterator<SelectionKey> keysIter = keys.iterator();
				while(keysIter.hasNext()) {
					SelectionKey it = keysIter.next();
					if(it!=service&&key!=it) {    //出去service和自己						
						it.attach(request);
						it.interestOps(it.interestOps()|SelectionKey.OP_WRITE);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void writable(SelectionKey key) {
		try{
			String tock = (String)key.attachment();
			key.attach("");
			
			SocketChannel sc = (SocketChannel)key.channel();
			sc.write(charset.encode(tock));
			
			key.interestOps(SelectionKey.OP_READ);
			
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		ChatService service = new ChatService();
		service.service();
		
	}

 2、客户端1

public class ClientC1 {

	private SocketChannel sc = null;
	private Charset charset = Charset.forName("UTF-8");
	private boolean ISRUN = true;
	
	public ClientC1() {
		try {
			sc = SocketChannel.open();
			sc.configureBlocking(false);
			InetAddress address = InetAddress.getLocalHost();
			InetSocketAddress isa = new InetSocketAddress(address, 9999);
			
			sc.connect(isa);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendMessage(String message) {
		
		try {
			System.out.println("aa:");
			while(!sc.finishConnect()) {}
			sc.write(charset.encode(message));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void receive() {
		try {
			//while(!sc.finishConnect()){};
			System.out.println("接收消息");
			while(ISRUN) {
				ByteBuffer buffer = ByteBuffer.allocate(1024);
				StringBuffer sb = new StringBuffer();
				
				while(sc.read(buffer)>0) {
					buffer.flip();
					sb.append(buffer.array());
					buffer.flip();
				}
				String str = sb.toString();
				if(str!=null&&!"".equals(str)) {					
					System.out.println("客户端接收信息:"+sb.toString());
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class ReceiveThread implements Runnable {
		@Override
		public void run() {
			try {
				while(ISRUN) {
					ByteBuffer buffer = ByteBuffer.allocate(1024);
					StringBuffer sb = new StringBuffer();
					
					while(sc.read(buffer)>0) {
						buffer.flip();
						sb.append(charset.decode(buffer));
						buffer.flip();
					}
					String str = sb.toString();
					if(str!=null&&!"".equals(str)) {					
						System.out.println("客户端接收信息:"+sb.toString());
					}
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void close() {
		
	}
	
	public static void main(String[] args) {
		ClientC1 c1 = new ClientC1();
		c1.sendMessage("hello client 1");
		//c1.receive();
		new Thread(c1.new ReceiveThread()).start();
	}
	
}

 3、客户端2

 

public class Client2 {

	private SocketChannel sc = null;
	private Charset charset = Charset.forName("UTF-8");
	private boolean ISRUN = true;
	
	public Client2() {
		try {
			sc = SocketChannel.open();
			sc.configureBlocking(false);
			InetAddress address = InetAddress.getLocalHost();
			InetSocketAddress isa = new InetSocketAddress(address, 9999);
			
			sc.connect(isa);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
   public void sendMessage(String message) {
		
		try {
			System.out.println("aa:");
			while(!sc.finishConnect()) {}
			sc.write(charset.encode(message));
			
			//sc.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void receive() {
		try {
			//while(!sc.finishConnect()){};
			while(ISRUN) {
				ByteBuffer buffer = ByteBuffer.allocate(1024);
				StringBuffer sb = new StringBuffer();
				
				while(sc.read(buffer)>0) {
					buffer.flip();
					sb.append(buffer.array());
					buffer.flip();
				}
				String str = sb.toString();
				if(str!=null&&!"".equals(str)) {					
					System.out.println("客户端接收信息:"+sb.toString());
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class ReceiveThread implements Runnable {
		@Override
		public void run() {
			try {
				while(ISRUN) {
					ByteBuffer buffer = ByteBuffer.allocate(1024);
					StringBuffer sb = new StringBuffer();
					
					while(sc.read(buffer)>0) {
						buffer.flip();
						sb.append(charset.decode(buffer));
						buffer.flip();
					}
					String str = sb.toString();
					if(str!=null&&!"".equals(str)) {					
						System.out.println("客户端接收信息:"+sb.toString());
					}
				}
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void close() {
		
	}
	
	public static void main(String[] args) {
		Client2 c2 = new Client2();
		c2.sendMessage("hello client 2_1");
		new Thread(c2.new ReceiveThread()).start();
	}
}

 

3、客户端3

public class Client3 {

	private SocketChannel sc = null;
	private Charset charset = Charset.forName("UTF-8");
	private boolean ISRUN = true;
	
	public Client3() {
		try {
			sc = SocketChannel.open();
			sc.configureBlocking(false);
			InetAddress address = InetAddress.getLocalHost();
			InetSocketAddress isa = new InetSocketAddress(address, 9999);
			
			sc.connect(isa);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 public void sendMessage(String message) {
			
			try {
				System.out.println("aa:");
				while(!sc.finishConnect()) {}
				sc.write(charset.encode(message));
				
				//sc.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		public void receive() {
			try {
				//while(!sc.finishConnect()){};
				while(ISRUN) {
					ByteBuffer buffer = ByteBuffer.allocate(1024);
					StringBuffer sb = new StringBuffer();
					
					while(sc.read(buffer)>0) {
						buffer.flip();
						sb.append(buffer.array());
						buffer.flip();
					}
					String str = sb.toString();
					if(str!=null&&!"".equals(str)) {					
						System.out.println("客户端接收信息:"+sb.toString());
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		public class ReceiveThread implements Runnable {
			@Override
			public void run() {
				try {
					while(ISRUN) {
						ByteBuffer buffer = ByteBuffer.allocate(1024);
						StringBuffer sb = new StringBuffer();
						
						while(sc.read(buffer)>0) {
							buffer.flip();
							sb.append(charset.decode(buffer));
							buffer.flip();
						}
						String str = sb.toString();
						if(str!=null&&!"".equals(str)) {					
							System.out.println("客户端接收信息:"+sb.toString());
						}
					}
				}catch(Exception e) {
					e.printStackTrace();
				}
			}
		}
		
	public static void main(String[] args) {
		Client3 client3 = new Client3();
		client3.sendMessage("hello client 3");
	}
}

 

 

 

 

相关标签: java nio 聊天