java noi socket

本文通过实例演示了如何使用Java NIO技术实现客户端与服务器之间的通信。包括自定义请求响应对象、序列化工具类及客户端和服务端的具体实现过程。

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


MyRequestObject.java


import java.io.Serializable;



public class MyRequestObject implements Serializable {
	private static final long serialVersionUID = 1L;

	private String name;
	
	private String value;

	private byte[] bytes;
	
	public MyRequestObject(String name, String value) {
		this.name = name;
		this.value = value;
		this.bytes = new byte[1024];
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
	
	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("Request [name: " + name  + ", value: " + value + ", bytes: " + bytes.length+ "]");
		return sb.toString();
	}
}


MyResponseObject.java

import java.io.Serializable;

public class MyResponseObject implements Serializable {

	private static final long serialVersionUID = 1L;

	private String name;
	
	private String value;

	private byte[] bytes;
	
	public MyResponseObject(String name, String value) {
		this.name = name;
		this.value = value;
		this.bytes = new byte[1024];
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
	
	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append("Response [name: " + name  + ", value: " + value + ", bytes: " + bytes.length+ "]");
		return sb.toString();
	}
}


SerializableUtil.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializableUtil {
	
	public static byte[] toBytes(Object object) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			return bytes;
		} catch(IOException ex) {
			throw new RuntimeException(ex.getMessage(), ex);
		} finally {
			try {
				oos.close();
			} catch (Exception e) {}
		}
	}
	
	public static Object toObject(byte[] bytes) {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(bais);
			Object object = ois.readObject();
			return object;
		} catch(IOException ex) {
			throw new RuntimeException(ex.getMessage(), ex);
		} catch(ClassNotFoundException ex) {
			throw new RuntimeException(ex.getMessage(), ex);
		} finally {
			try {
				ois.close();
			} catch (Exception e) {}
		}
	}
}


zwyClient.java

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
/*noi的客户端*/
public class zwyClient {
    /*日志获取*/
	private final static Logger logger = Logger.getLogger(zwyClient.class.getName());
	
	public static void main(String[] args) throws Exception {
		for (int i = 0; i < 3; i++) {
			final int x = i ; 
			/*创建3个请求*/
			new Thread(new MyRunnable(x)).start();
		}
	}
	
	private static final class MyRunnable implements Runnable {

			private final int idx;
			public MyRunnable(int x){
				this.idx = x;
			}
			public void run(){
				SocketChannel socketChannel = null;
				try{
					socketChannel = SocketChannel.open();
					/*创建服务器的socket地址*/
					SocketAddress socketAddress = new InetSocketAddress("127.0.0.1",10000);
					/*链接服务器*/
					socketChannel.connect(socketAddress);
					MyRequestObject myRequestObject = new MyRequestObject("reqeust_" + idx, "reqeust_" + idx);
					logger.log(Level.INFO, myRequestObject.toString());
					/*发送数据*/
					sendData(socketChannel, myRequestObject);
					
					MyResponseObject myResponse = receiveData(socketChannel);
					logger.log(Level.INFO, myResponse.toString());
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					try {
						socketChannel.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			}
			private void sendData(SocketChannel socketChannel, MyRequestObject myRequestObject) throws IOException {
				/*转成byte数组,*/
				byte[] bytes = SerializableUtil.toBytes(myRequestObject);
				ByteBuffer buffer = ByteBuffer.wrap(bytes);
				/*装载到缓冲区中*/
				socketChannel.write(buffer);
				/*缓冲区写入完成,关闭输出流.*/
				socketChannel.socket().shutdownOutput();

			}

			private MyResponseObject receiveData(SocketChannel socketChannel) throws Exception {
				MyResponseObject myResponse = null;
				ByteArrayOutputStream baos = new ByteArrayOutputStream();;
				ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
				byte[] bytes;
				/*接受数据*/
				int count = 0 ; 
				while( (count = socketChannel.read(buffer)) >= 0 ){
					buffer.flip();
					bytes = new byte[count];
					buffer.get(bytes);
					baos.write(bytes);
					buffer.clear();
				}
				bytes = baos.toByteArray();
				Object obj = SerializableUtil.toObject(bytes);/*反序列化为对象*/
				myResponse = (MyResponseObject)obj;
				/*关闭接受数据流*/
				socketChannel.socket().shutdownInput();
				baos.close();
				return myResponse;
			}
		}

		
}


zwyServer.java

import java.io.ByteArrayOutputStream;
import java.io.IOException;
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.logging.Level;
import java.util.logging.Logger;
/*noi的服务器*/
public class zwyServer {
	/*获取日志*/
	private final static Logger logger = Logger.getLogger(zwyServer.class.getName());
	
	public static void main(String[] args) throws Exception{
		Selector selector = null;
		ServerSocketChannel serverSocketChannel = null;
		selector = Selector.open();/*创建Selector*/

		/*创建一个serverSocket的通道*/
		serverSocketChannel = ServerSocketChannel.open();
		/*设置为非阻塞,才能向Selector注册.*/
		serverSocketChannel.configureBlocking(false);
		
		serverSocketChannel.socket().setReuseAddress(true);
		serverSocketChannel.socket().bind(new InetSocketAddress(10000));
		/*将serverChannel注册到Selector中,注册接受事件.
		 * 
		SelectionKey.OP_ACCEPT;
		SelectionKey.OP_CONNECT;
		SelectionKey.OP_READ;
		SelectionKey.OP_WRITE;
		对不止一件事情感兴趣可以用 | 进行连接
		例如SelectionKey.OP_READ | SelectionKey.OP_WRITE;
		*/
		serverSocketChannel.register(selector , SelectionKey.OP_ACCEPT);
		/*阻塞知道有注册的时间发生*/
		while(selector.select() > 0 ){
			Iterator<SelectionKey> it = selector.selectedKeys().iterator();
			/*时间迭代器*/
			while(it.hasNext()){
				SelectionKey readyKey = it.next();
				it.remove();
				/*移除并处理时间*/
				execute((ServerSocketChannel) readyKey.channel());
			
			}
		}
		selector.close();

		serverSocketChannel.close();

		
	}

	private static void execute(ServerSocketChannel serverSocketChannel) throws Exception {
		SocketChannel socketChannel = null;
		 socketChannel = serverSocketChannel.accept();
		 /*连接*/
		 MyRequestObject myRequestObject = receiveData(socketChannel); /*接受数据*/

		 logger.log(Level.INFO,myRequestObject.toString());
		 
		 MyResponseObject myResponserObject = new MyResponseObject(
			"responser for" + myRequestObject.getName(),
			 "responser for "+myRequestObject.getValue());
		 /*返回数据*/
		 sendData(socketChannel,myResponserObject);
		 logger.log(Level.INFO, myResponserObject.toString());
	}
	
	private static MyRequestObject receiveData(SocketChannel socketChannel) throws Exception {
		MyRequestObject myRequestObject = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		ByteBuffer buffer = ByteBuffer.allocate(1024);
		
		byte[]  bytes = null;
		int size = 0 ; 
		while((size = socketChannel.read(buffer)) >= 0){
			buffer.flip();
			bytes = new byte[size];
			buffer.get(bytes);
			baos.write(bytes);
			buffer.clear();
		}
		
		bytes = baos.toByteArray();
		Object obj = SerializableUtil.toObject(bytes);
		myRequestObject = (MyRequestObject) obj;
		baos.close();
		socketChannel.socket().shutdownInput();
		return myRequestObject;

	}

	private static void sendData(SocketChannel socketChannel, MyResponseObject myResponseObject) throws IOException {
		byte[] bytes = SerializableUtil.toBytes(myResponseObject);
		ByteBuffer buffer = ByteBuffer.wrap(bytes);;
		socketChannel.write(buffer);
		socketChannel.socket().shutdownOutput();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值