using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DotNetty.Transport.Bootstrapping; using DotNetty.Transport.Channels; using DotNetty.Buffers; namespace nettyCommunication { public class Communication:ICommunication { private IChannelHandlerContext ctx = null; public Communication(IChannelHandlerContext ctx) { this.ctx = ctx; } public void Connection() { //连接,并注册初始化。 try { ClientDemo.RunClientAsync().Wait(); } catch (Exception) { Console.WriteLine("服务没有开启,请检查服务器"); } } public void SendMessage(object message) { var mess = message as MessageUTF8; IByteBuffer initialMessage = Unpooled.Buffer(ClientSettings.Size); byte[] byteMessage = JsonByByteToObjectTools.ObjToJsonByte(mess); initialMessage.WriteBytes(byteMessage); ctx.WriteAndFlushAsync(initialMessage); } public AbstractMessage ReceiveMessage(object message) { try { AbstractMessage msg = null; IByteBuffer byteBuffer = message as IByteBuffer; byteBuffer.AdjustCapacity(1024); byteBuffer.SetWriterIndex(256); byte[] bytes = new byte[256]; byteBuffer.SetReaderIndex(0); byteBuffer.ReadBytes(bytes); byteBuffer.Clear(); MessageUTF8 mess = (MessageUTF8)JsonByByteToObjectTools.JsonByteToObj(bytes); if (mess != null) { msg = mess; } else { msg = null; } return msg; } catch(Exception) { Console.WriteLine("消息对象转换存在问题,可能是服务器没有发送消息对象!"); return null; } } public void Close() { throw new NotImplementedException(); } } }