TCP通信 netty写服务端 一下是代码
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(new TcpServerHandler());
ChannelFuture f = b.bind(8080).sync();
System.out.println("服务端已启动,等待客户端连接..");
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
public class TcpServerHandler extends ChannelInboundHandlerAdapter {
// 接收到新的数据
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException {
try {
// 接收客户端的数据
ByteBuf in = (ByteBuf) msg;
System.out.println("channelRead:" + in.toString(CharsetUtil.UTF_8));
// 发送到客户端
byte[] responseByteArray = "hello".getBytes("UTF-8");
ByteBuf out = ctx.alloc().buffer(responseByteArray.length);
out.writeBytes(responseByteArray);
ctx.writeAndFlush(out);
//ctx.write("hello");
} finally {
ReferenceCountUtil.release(msg);
@Override
public void channelActive(ChannelHandlerContext ctx) throws UnsupportedEncodingException{
System.out.println("channelActive:" + ctx.channel().remoteAddress());
ChannelGroups.add(ctx.channel());
@Override
public void channelInactive(ChannelHandlerContext ctx) {
System.out.println("channelInactive:" + ctx.channel().remoteAddress());
ChannelGroups.discard(ctx.channel());
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
Delphi indy10写的客户端
procedure TForm1.BtnSendClick(Sender: TObject);
AStream: TStringStream;
begin
LbLog.Items.Add(EdtData.Text);
with IdTCPClient do
begin
IOHandler.WriteLn('DATA ' + EdtData.Text);
if IOHandler.InputBufferIsEmpty then
begin
ShowMessage('InputBufferIsEmpty');
begin
LbLog.Items.Add(IOHandler.ReadLn);
AStream := TStringStream.Create;
IOHandler.ReadStream(AStream);
except
LbLog.Items.Add('发送数据失败!');
IdTCPClient.Disconnect();
IdTCPClient.Free;
LbLog.Items.Add('同主机' + EdtHost.Text + '的连接已断开!');
BtnConnect.Enabled := True;
BtnSend.Enabled := False;
BtnDisconnect.Enabled := False;
end; // end try
end; // end with
客户端能连接服务端 而且能发送消息 但是就是获取不到服务端返回的数据。应该往哪个方向去差原因,或者还有没有其他的方式去实现?要求就是服务端需要是Java 客户端要Delphi。
下了你的工具作客户端发送时报错了 但是重新下了一个sokit作客户端和我写的NETTY服务端是能交互成功的,但是做服务端和我的客户端交互,Delphi写的客户端发送数据就会卡死。