private static void Conect() { IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; // створення об’єкту порт+ IP-адреса IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12000); Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listener.Bind(localEndPoint); while (true) { listener.Listen(100); Socket handler = listener.Accept(); byte[] bytes = new byte[100000]; int count; // String data = " "; // отримання та надсилання даних count = handler.Receive(bytes); rs = (RiskManagementLib)Convertor.ByteArrayToObject(bytes, count); if (!Check()) { rs.isCorrect = 0; } Console.WriteLine("До БД доступається " + rs.Login); Byte[] SendBytes = Convertor.ObjectToByteArray(rs); handler.Send(SendBytes); handler.Shutdown(SocketShutdown.Both); handler.Close(); } }
/// <summary> /// 广播消息 queue自动生成 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="handler"></param> public void SubscribeFanout <T>(Action <T> handler) where T : Messages { var queueInfo = GetRabbitMqAttribute <T>(); if (queueInfo.IsNull()) { throw new ArgumentException(RabbitMqAttribute); } var channel = _connection.CreateModel(); ExchangeDeclare(channel, queueInfo.ExchangeName, ExchangeType.Fanout, queueInfo.IsProperties); string queue = channel.QueueDeclare().QueueName; channel.QueueBind(queue, queueInfo.ExchangeName, ""); _publishModelDic[queue] = channel; _exchangeQueue[queueInfo.ExchangeName] = queue; var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var obj = Convertor.ByteArrayToObject(body, true); var msg = obj as T; try { if (msg.Queues != _exchangeQueue[queueInfo.ExchangeName]) { handler(msg); Console.WriteLine(string.Format("Subscribe:{0}-{1}", queueInfo.ExchangeName, queue)); } else { Console.WriteLine("自动发布自己"); } } catch (Exception ex) { //_logWriter.Write(string.Format("消息接收失败:{0}", ex.Message)); } finally { channel.BasicAck(ea.DeliveryTag, false); } }; channel.BasicConsume(queue, false, consumer); }
private static void server_OnDataReceived(object sender, NetConnection connection, byte[] e) { if (e.Length > 0) { NetworkData ReceivedData = (NetworkData)Convertor.ByteArrayToObject(e); switch (ReceivedData.ComReason) { case Reason.Login: GoogleTOTP tf = new GoogleTOTP(); LoginData LoginCredentials = (LoginData)ReceivedData.Data; if (UserDB.ContainsKey(LoginCredentials.User)) { User client = UserDB[LoginCredentials.User]; if (client.passwd == LoginCredentials.Password) // && tf.GeneratePin(client.code) == LoginCredentials.Code { LogData(connection.RemoteEndPoint + " login as " + LoginCredentials.User); connection.Send(Tools.Convertor.ObjectToByteArray(new Tools.NetworkData() { ComReason = Tools.Reason.Response, Data = "lgins" })); } else { LogData(connection.RemoteEndPoint + " failed to login as " + LoginCredentials.User); connection.Send(Tools.Convertor.ObjectToByteArray(new Tools.NetworkData() { ComReason = Tools.Reason.Response, Data = "lginf" })); } } else { LogData(connection.RemoteEndPoint + " user not found " + LoginCredentials.User); connection.Send(Tools.Convertor.ObjectToByteArray(new Tools.NetworkData() { ComReason = Tools.Reason.Response, Data = "lginnf" })); } break; case Reason.Com: break; default: break; } } }
public static bool SendToServer(RiskManagementLib rs) { string response = ""; rs.isCorrect = 2; Byte[] SendBytes = Convertor.ObjectToByteArray(rs);//ObjectToByteArray(message); Byte[] RecvBytes = new byte[100000]; int count; // визначення адреси сервера IPAddress address = Dns.Resolve("localhost").AddressList[0]; // встановлення порту IPEndPoint EPhost = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12000); // формуваннняоб’єкту Socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // З’єднання з сервером try { socket.Connect(EPhost); // пересилання ти приймання даних socket.Send(SendBytes, SendBytes.Length, SocketFlags.None); count = socket.Receive(RecvBytes); rs = (RiskManagementLib)Convertor.ByteArrayToObject(RecvBytes, count); if (rs.isCorrect == 0) { return(false); } return(true); } catch (Exception error) { MessageBox.Show("Error - " + error); } return(false); }
/// <summary> /// 接收消息 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queue">队列名称</param> /// <param name="isProperties"></param> /// <param name="handler">消费处理</param> /// <param name="isDeadLetter"></param> public void Subscribe <T>(string exchangeName, string queue, bool isProperties, Action <T> handler, bool isDeadLetter) where T : Messages { //队列声明 var channel = GetModel(exchangeName, queue, isProperties); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; //var msgStr = SerializeExtension.DeserializeUtf8(body); //var msg = msgStr.FromJson<T>(); var obj = Convertor.ByteArrayToObject(body, true); var msg = obj as T; try { handler(msg); } catch (Exception ex) { //TODO:订阅失败处理 //_logWriter.Write(string.Format("消息接收失败:{0}", ex.Message)); //if (ex.InnerException != null) //{ // _logWriter.Write(string.Format("消息接收失败InnerException:{0}", ex.InnerException.Message)); //} //if (!isDeadLetter) // PublishToDead<DeadLetterQueue>(queue, msgStr, ex); } finally { channel.BasicAck(ea.DeliveryTag, false); } }; //- 自动应答 //消费者确认或者说消费者应答指的是RabbitMQ需要确认消息到底有没有被收到 channel.BasicConsume(queue, false, consumer); }