Java——SocketChannel

       SocketChannel是NIO形式的客户端服务器通信的形式,支持异步非阻塞连接,通过管道与缓存的形式进行通信,与Java的Socket是有区别的,socket是通过请求——连接的形式进行通信,而SocketChannel是通过建立管道的形式进行通信,原则上,SocketChannel要比Socket快,这只是自己的理解,不知道正确与否了。。。下面总结下SocketChannel形式的代码实现:

 

一、服务器端:

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelTest {

	public static void main(String[] args) throws Exception {
		
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  
		serverSocketChannel.socket().bind(new InetSocketAddress(9999));  
		while(true){  
		    SocketChannel socketChannel = serverSocketChannel.accept();  
		    ByteBuffer buf = ByteBuffer.allocate(48);  
		    int bytesRead = socketChannel.read(buf);  
		   
		    while (bytesRead != -1) {  
		    	  
		    	System.out.println("Read " + bytesRead);  
		    	buf.flip();  
		    	  
		    	while(buf.hasRemaining()){  
		    		System.out.print((char) buf.get());  
		    	}  
		    	  
		    	buf.clear();  
		    	bytesRead = socketChannel.read(buf);  
		    }  
		}  
	}
}

 这个阻塞的形式,也就是在serverSocketChannel.accept();处,只有当客户端有请求进行通道链接时,才会向下执行,下面是非阻塞形式的代码:

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  
		serverSocketChannel.socket().bind(new InetSocketAddress(9999));  
		serverSocketChannel.configureBlocking(false);  //设置为非阻塞式
		while(true){  
		    SocketChannel socketChannel = serverSocketChannel.accept();  
		    if(socketChannel != null){  //为非阻塞式时,要进行非空判断
		        //do something with socketChannel...  
		    }  
		}  

  二、客户端代码:

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class SocketChannelTest {
	
	public static void main(String[] args) throws Exception {
		
		SocketChannel socketChannel = SocketChannel.open();
		socketChannel.connect(new InetSocketAddress("localhost", 9999));
		
		String newData = "New String to write to socket...." + System.currentTimeMillis(); 
		ByteBuffer buf = ByteBuffer.allocate(48);
		buf.clear();
		buf.put(newData.getBytes());
		buf.flip();
		  
		while(buf.hasRemaining()) {
			socketChannel.write(buf);
		}
		
		socketChannel.close();
	}
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值