使用new io 的socket
服务器端(非阻塞):
package org.snake.socket;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SocketChannel;public class Client {private static final int DEFAULT_PORT = 12346;private static final String DEFAULT_IP = "localhost";private static final String HELLO = "Hello,Server";public static void main(String[] args) throws IOException{SocketChannel sc = SocketChannel.open();InetSocketAddress ina = new InetSocketAddress(DEFAULT_IP, DEFAULT_PORT);sc.connect(ina);// 该方法会阻塞,因为该通道为阻塞模式//写到服务器ByteBuffer buff = ByteBuffer.allocate(128);buff.put(HELLO.getBytes());buff.flip();sc.write(buff);//读取服务器buff.clear();sc.read(buff);buff.flip();while(buff.hasRemaining()) {System.out.print((char)buff.get());}sc.close();//关闭通道}}