There is a server on java + netty.io

ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { //Здесь указываем размер буфера (8192 байта) и символ-признак конца пакета. //Свои пакеты мы обычно терминируем символом с кодом 0, что соответствует nulDelimiter() в терминологии нетти ch.pipeline().addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.nulDelimiter())); ch.pipeline().addLast("decoder", new StringDecoder()); //Стандартный строковый декодер. ch.pipeline().addLast("encoder", new StringEncoder()); ch.pipeline().addLast("hendler", new ServerHandler()); } }) .option(ChannelOption.TCP_NODELAY,true) .option(ChannelOption.SO_KEEPALIVE,true); ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(this.PORT)).sync(); LoggingSystem.getLogger().log(Level.INFO,"NettyServer: Listen to users on "+ InetAddress.getLocalHost().toString()+":"+ this.PORT+"\n"); // Wait until the server socket is closed. // In this example, this does not happen, but you can do that to gracefully // shut down your server. channelFuture.channel().closeFuture().sync(); 

Message handling

  @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { //Вызывается когда от клиента приходит очередной пакет. try { new CommandProcessorSmall("cmdProcessor", new MsgChannel(ctx.channel(),msg.toString()),_debug).start(); }catch (Exception ex) {ex.printStackTrace();} } 

Thread handler

  @Override public void run() { try { if (_debug) { LoggingSystem.getLogger().log(Level.DEBUG,"IN > "+msgChannel.message+"\n"); } //Варианты ответов //String response = (String)_combat.processCommand(_nCtx); //Игровая логика генерирует ответ //String response = "{\"resp\":\"Anwer in JSON format\"}"; //JSON String response = "<resp>Answer in XML format</resp>"; //XML ((Channel)(msgChannel.channel)).write(response+"\0"); if (_debug) { LoggingSystem.getLogger().log(Level.DEBUG,"OUT > "+response+"\n"); } } catch (Exception e) { e.printStackTrace(); } } 

All the logic is that each pocket has at the end 0. And after receiving the packet, we process it in the stream created for it, and call the response back to the client.

The server works great. But the client, I do not like I can not connect from the C # code, send and read the message. This is how I can send, the server sees and outputs to the log, but I do not get the answer back.

  static void Main(string[] args) { // Буфер для входящих данных byte[] bytes = new byte[8192]; // Соединяемся с удаленным устройством // Устанавливаем удаленную точку для сокета IPHostEntry ipHost = Dns.GetHostEntry("localhost"); IPAddress ipAddr = ipHost.AddressList[0]; IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 7777); Socket sender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Соединяем сокет с удаленной точкой sender.Connect(ipEndPoint); string message = "Hi server"+"\0" Console.WriteLine("Сокет соединяется с {0} ", sender.RemoteEndPoint.ToString()); byte[] msg = Encoding.UTF8.GetBytes(message); // Отправляем данные через сокет int bytesSent = sender.Send(msg); // Получаем ответ от сервера int bytesRec = sender.Receive(bytes); Console.WriteLine("\nОтвет от сервера: {0}\n\n", Encoding.UTF8.GetString(bytes, 0, bytesRec)); // Освобождаем сокет sender.Shutdown(SocketShutdown.Both); sender.Close(); } 

I suspect the whole problem is packet separation. because the server generates a packet in which the latter goes 0. And the client divides the packet like this: Encoding.UTF8.GetString (bytes, 0, bytesRec)

How to be? How to send a message and get an answer?

    1 answer 1

    I figured it out myself)) the whole problem was in the server. He just did not send the answer. And the fact was that I wrote data to the stream, but did not send using the wrong methods of Netty. It was necessary to replace

     ctx.write(obj msg) 

    on

     ctx.writeAndFlush(obj msg)