一,服务端以下方式读取数据,则发送的数据必须以换行符/n结尾
String msg = reader.readLine()
1.我们在客户端只要使用传统的客户端编写方式即可
package com.netty.study.nettystart.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.channel.socket.oio.OioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class NettyClient {
public static void main(String[] args) {
EventLoopGroup group = new OioEventLoopGroup();
try {
ChannelFuture nettyclient_连接陈工 = new Bootstrap()
.group(group)
.channel(OioSocketChannel.class)
.remoteAddress(new InetSocketAddress("127.0.0.1",9746))
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel nioSocketChannel) throws Exception {
// nioSocketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
nioSocketChannel.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String message = "Hello Server\n";
ByteBuf buffer = Unpooled.copiedBuffer(message.getBytes());
ctx.writeAndFlush(buffer);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.channel().close();
}
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
System.out.println(byteBuf.toString(Charset.defaultCharset()));
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
super.channelRegistered(ctx);
}
});
}
}).connect().sync();
nettyclient_连接陈工.channel().closeFuture().sync();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
group.shutdownGracefully();
}
}
}
2.服务端代码
package com.netty.study.nettystart.server;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class SimpleSocketServer {
private static final int PORT = 9746;
public static void main(String[] args) throws IOException {
final String QUIT = "quit";
final int DEFAULT_PORT = 9746;
ServerSocket serverSocket = null;
BufferedReader reader = null;
BufferedWriter writer = null;
try {
// 绑定监听端口
serverSocket = new ServerSocket(DEFAULT_PORT);
System.out.println("启动服务器,监听服务器本地端口" + DEFAULT_PORT);
while (true) {
// 等待客户端连接
Socket socket = serverSocket.accept();
System.out.println("客户端["+socket.getInetAddress()+":"+ socket.getPort() + "]已连接");
InputStream inputStream = socket.getInputStream();
reader = new BufferedReader(
new InputStreamReader(inputStream)
);
writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())
);
String msg = reader.readLine();
while (msg != null) {
// 读取客户端发送的消息
System.out.println("客户端["+socket.getInetAddress()+":"+ socket.getPort() + "]: " + msg);
// 回复客户发送的消息
writer.write("服务器已收到: " + msg + "\n");
//防止消息遗留到本地缓冲区,保证马上发送出去
writer.flush();
// 查看客户端是否退出
if (QUIT.equalsIgnoreCase(msg)) {
System.out.println("客户端["+socket.getInetAddress()+":"+ socket.getPort() + "]已断开连接");
break;
}
}
// System.out.println(decodedData+"_----------------------------------");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
reader.close();
writer.close();
System.out.println("关闭serverSocket");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
二,服务端直接以字节数组接收
1.客户端代码和上边一样,唯一的区别就是,不需要固定结尾的/n了,随便发送即可
2.服务端代码:
package com.netty.study.nettystart.server;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class SimpleSocketServer {
private static final int PORT = 9746;
public static void main(String[] args) throws IOException {
final String QUIT = "quit";
final int DEFAULT_PORT = 9746;
ServerSocket serverSocket = null;
BufferedReader reader = null;
BufferedWriter writer = null;
try {
// 绑定监听端口
serverSocket = new ServerSocket(DEFAULT_PORT);
System.out.println("启动服务器,监听服务器本地端口" + DEFAULT_PORT);
while (true) {
// 等待客户端连接
Socket socket = serverSocket.accept();
System.out.println("客户端["+socket.getInetAddress()+":"+ socket.getPort() + "]已连接");
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = inputStream.read(buffer); // 读取字节数据
byte[] receivedData = Arrays.copyOf(buffer, bytesRead); // 接收到的字节数据
// 解码操作,例如将字节数组转换为字符串
String decodedData = new String(receivedData, StandardCharsets.UTF_8);
System.out.println("消息:"+decodedData+"_----------------------------------");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
reader.close();
writer.close();
System.out.println("关闭serverSocket");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}