123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- 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;
- using System.Threading;
- namespace nettyCommunication
- {
- class Program
- {
- private static Communication comm = null;
- private static Thread receiveMsg = null;
- private static bool connected { get; set; }
- static void Main(string[] args)
- {
- //持续进行连接尝试
- Task.Factory.StartNew(() =>
- {
- //初始化后与web持续连接
- while (true)
- {
- try
- {
- Connections.close();
- Connections.Connection();
- connected = true;
- comm = new Communication();
- break;
- }
- catch (Exception)
- {
- connected = false;
- Console.WriteLine("服务没有开启,请检查服务器");
- }
- Thread.Sleep(200);
- }
- //持续判断连接状态并重连
- while (true)
- {
- Console.WriteLine(Connections.isAlive() + ", " + receiveMsg.ThreadState.ToString());
- if (Connections.isAlive())
- {
- if (!connected)
- {
- comm = new Communication();
- }
- connected = true;
- if (receiveMsg.ThreadState == ThreadState.Aborted)
- {
- try
- {
- receiveMsg.Start();
- }
- catch (Exception ex) { Console.WriteLine(ex.Message); }
- }
- }
- else
- {
- connected = false;
- try
- {
- if (receiveMsg.ThreadState == ThreadState.WaitSleepJoin)
- {
- receiveMsg.Interrupt();
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("连接断开,终止消息接收线程");
- }
- Console.WriteLine(" 连接关闭,需要重新连接注册");
- try
- {
- Connections.close();
- Connections.Connection();
- }
- catch (Exception)
- {
- Console.WriteLine("服务没有开启,请检查服务器");
- }
- }
- Thread.Sleep(200);
- }
- });
- //持续接收消息
- receiveMsg = new Thread(() =>
- {
- while (true)
- {
- try
- {
- if (connected && comm != null)
- {
- MessageUTF8 msg = ((MessageUTF8)comm.ReceiveMessage());
- }
- }
- catch { Console.WriteLine("线程已中断"); }
- }
- });
- receiveMsg.Start();
- Console.ReadLine();
- }
- //public static async Task sendMessage(IChannelHandlerContext ctx,object message)
- //{
- // AbstractMessage ms = (AbstractMessage)message;
- // IByteBuffer initialMessage = Unpooled.Buffer(ClientSettings.Size);
- // //byte[] messageByte = Encoding.UTF8.GetBytes(msg);
- // byte[] byteMessage = JsonByByteToObjectTools.ObjToJsonByte(ms);
- // initialMessage.WriteBytes(byteMessage);
- // await ctx.WriteAndFlushAsync(initialMessage);
- // ctx.Flush();
- //}
- }
- }
|