天天看點

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();
	}
}