使用Channel(通道)使客户端和服务器通话:

SocketChannel和ServerSocketChannel的实现通信

客户端:
public class Test08 {
public static void main(String[] args) throws IOException {
//1.创建SocketChannel
SocketChannel socketChannel = SocketChannel.open();
//2.去连接服务器
boolean b = socketChannel.connect(new InetSocketAddress(“192.168.3.54”, 5555));
//3.判断
if(b){
//4.发送数据
System.out.println(“连接服务器成功…”);
ByteBuffer byteBuffer = ByteBuffer.wrap(“Hello,我是客户端…”.getBytes());
socketChannel.write(byteBuffer);
//5.读取数据
ByteBuffer buffer = ByteBuffer.allocate(1024);
int read = socketChannel.read(buffer);
//切换模式
buffer.flip();
System.out.println(new String(buffer.array(),0,read));
//6.释放资源
socketChannel.close();
}
}
}
服务器:
public class Test07 {
public static void main(String[] args) throws IOException {
//1.创建ServerSocketChannel对象
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//2.绑定本地的地址
serverSocketChannel.bind(new InetSocketAddress(“192.168.3.54”,6666));
//3.接收客户端
SocketChannel socketChannel = serverSocketChannel.accept();
System.out.println(“有客户端连接了…”);
//4.读取数据
ByteBuffer buffer = ByteBuffer.allocate(1024);
int len = socketChannel.read(buffer);
//5.打印数据
buffer.flip();//先把byteBuffer切换为读模式
String str = new String(buffer.array(),0,len);
System.out.println(“客户端说:”+str);
//6.回数据
ByteBuffer buffer1 = ByteBuffer.allocate(1024);
buffer1.put(“Hello,我是服务器…”.getBytes());
//7.切换模式
buffer1.flip();
socketChannel.write(buffer1);
//8.释放资源
socketChannel.close();
serverSocketChannel.close();
}
}

你可能感兴趣的:(笔记)