/// <summary> /// Join a topic /// </summary> /// <param name="customPacket">Packet received</param> /// <returns>Packet to send</returns> private CustomPacket JoinTopic(CustomPacket customPacket) { Operation op = Operation.Reception; string message = "Added to topic " + (Topic)customPacket.Data; var topicList = Server.TopicList.SearchTopic((Topic)customPacket.Data); // We check if the topic exist if (topicList != null) { // We check if the user can join this topic if (topicList.SearchUser(_user) == null) { topicList.AddUser(_user); } else { op = Operation.Refused; message = "You are already in " + (Topic)customPacket.Data; } } else { op = Operation.Refused; message = (Topic)customPacket.Data + " does not exists"; } return(new CustomPacket(op, new InformationMessage(message))); }
/// <summary> /// Handle an user /// </summary> /// <param name="username">username</param> /// <param name="password">password</param> /// <param name="message">Information message</param> /// <param name="packetCreation">Function to handle packet creation</param> /// <returns>Validity of operation</returns> public bool HandleUser(string username, string password, out string message, PacketCreation packetCreation) { message = null; var u = new User { Username = username, Password = password }; _customPacket = packetCreation(u); try { Net.sendMsg(Client.Connection.GetStream(), _customPacket); _customPacket = Net.rcvMsg(Client.Connection.GetStream()); message = GetInformationMessage(); if (_customPacket.Operation == Operation.Reception) { return(true); } } catch (Exception e) { message = "Connection failed"; Console.Out.WriteLine("Error: " + e); } // We set User to null, because the LoginUserPacket() set it to the value of the user Client.CurrentUser = null; return(false); }
public void WriteToCustomPacket(CustomPacket packet) { byte flags = 0; flags |= (byte)((byte)Reliability << FLAG_RELIABILITY_INDEX); flags |= Split ? FLAG_SPLIT : (byte)0; packet.WriteByte(flags); packet.WriteUShort((ushort)(Payload.Length * 8)); if (Reliability.IsReliable()) { packet.WriteTriad(MessageIndex, ByteOrder.Little); } if (Reliability.IsOrdered() || Reliability.IsSequenced()) { packet.WriteTriad(OrderIndex, ByteOrder.Little); packet.WriteByte(OrderChannel); } if (Split) { packet.WriteInt(SplitCount); packet.WriteUShort(SplitId); packet.WriteInt(SplitIndex); } packet.WriteBytes(Payload); }
/// <summary> /// Leave a topic /// </summary> /// <param name="customPacket">Packet received</param> /// <returns>Packet to send</returns> private CustomPacket LeaveTopic(CustomPacket customPacket) { Operation op = Operation.Reception; string message = "Disconnected from topic " + (Topic)customPacket.Data; var topicList = Server.TopicList.SearchTopic((Topic)customPacket.Data); // We check if the topic exist if (topicList != null) { // We check if the user can join this topic if (topicList.SearchUser(_user) != null) { topicList.RemoveUser(_user); } else { op = Operation.Refused; message = "You are not in " + (Topic)customPacket.Data; } } else { op = Operation.Refused; message = (Topic)customPacket.Data + " does not exists"; } return(new CustomPacket(op, new InformationMessage(message))); }
public EncapsulatedPacket(CustomPacket packet) { byte flags = packet.ReadByte(); Reliability = (Reliability)((flags & FLAG_RELIABILITY) >> FLAG_RELIABILITY_INDEX); Split = (flags & FLAG_SPLIT) > 0; int length = packet.ReadUShort() / 8; if (Reliability.IsReliable()) { MessageIndex = packet.ReadTriad(ByteOrder.Little); } if (Reliability.IsOrdered() || Reliability.IsSequenced()) { OrderIndex = packet.ReadTriad(ByteOrder.Little); OrderChannel = packet.ReadByte(); } if (Split) { SplitCount = packet.ReadInt(); SplitId = packet.ReadUShort(); SplitIndex = packet.ReadInt(); } Payload = packet.ReadBytes(length); }
/// <summary> /// Log an user /// </summary> /// <param name="customPacket">Packet received</param> /// <returns>Packet to send</returns> private CustomPacket LoginUser(CustomPacket customPacket) { User u = (User)customPacket.Data; Server.AllUsers.Semaphore.WaitOne(); var searchedUser = Server.AllUsers.SearchUser(u); Server.AllUsers.Semaphore.Release(); string errorMessage = ""; if (searchedUser != null) // No need to check for credentials, SearchUser already did it { if (Server.ConnectedUsers.SearchUser(searchedUser) == null) // No double connection { Server.ConnectedUsers.Semaphore.WaitOne(); Server.ConnectedUsers.AddUser(u); _user = u; Server.TcpClients.Add(_user, comm); Server.ConnectedUsers.Semaphore.Release(); Connecting(); return(new CustomPacket(Operation.Reception, new InformationMessage("Connected"))); } errorMessage = "You are already connected"; } else { errorMessage = "Wrong credentials"; } return(new CustomPacket(Operation.Refused, new InformationMessage(errorMessage))); }
/// <summary> /// Connecting user /// </summary> private void Connecting() { CustomPacket pck = new CustomPacket(Operation.Reception, new InformationMessage(_user.Username + " is now connected")); Broadcast(pck, Server.ConnectedUsers); }
public static void Push(CustomPacket packet) { lock (m_lockBuffer) { m_pool.Push(packet); } }
/// <summary> /// Loop handling listener /// </summary> private void Loop() { while (CurrentUser != null && _connection != null) { try { // Listening CustomPacket customPacket = Net.rcvMsg(_connection.GetStream()); AddLineChat(customPacket.ToString()); _connectTry = 0; } catch (Exception) { // Fail // If the client connection is null, it means that there has been a logout if (_connection != null) { if (CurrentUser != null) { AddLineChat("Connection error"); } Timeout(); } } } }
public void HandleCustomHandle(CustomPacket packet) { SendAck(packet.SequenceId); uint handleSeq = packet.SequenceId + 1; uint diff = handleSeq - ReceiveSequenceNumber; if (ReceiveSequenceNumber < handleSeq) { if (diff != 1) { for (uint i = ReceiveSequenceNumber; i < ReceiveSequenceNumber + diff - 1; i++) { SendNack(i - 1); } } ReceiveSequenceNumber = handleSeq; for (int i = 0; i < packet.Packets.Length; i++) { HandleEncapsulatedPacket(packet.Packets[i]); } } }
/// <summary> /// Loop handling listener /// </summary> public void Loop() { while (Client.CurrentUser != null && Client.Connection != null) { try { // Listening CustomPacket customPacket = Net.rcvMsg(Client.Connection.GetStream()); if (customPacket == null) { continue; } Console.Out.WriteLine(customPacket.ToString()); _connectTry = 0; } catch (Exception) { // Fail // If the client connection is null, it means that there has been a logout if (Client.Connection != null) { if (Client.CurrentUser != null) { Console.Out.WriteLine("Connection error"); } Timeout(); } } } }
public override CustomPacket Commands(CustomPacket packet, TcpClient client) { CustomPacket responsePacket = null; var watch = Stopwatch.StartNew(); switch(packet.Command) { case "scan": _log.Information($"Incoming scan from: {client.Client.RemoteEndPoint}"); responsePacket = Scan(packet); break; case "getBIN": responsePacket = getBin(packet); break; case "showMissing": responsePacket = showMissing(packet); break; case "disposeCache": using (var _db = new ZEMDBContext()) { var stray = _db.ScanCache.Find((Guid)packet.Payload); if (stray != null) _db.Remove(stray); _db.SaveChanges(); responsePacket = new CustomPacket(FlagType.basic, HeaderTypes.basic, "disposeCache", null, null); } break; } watch.Stop(); _log.Information($"Command {packet.Command} execution time [{watch.ElapsedMilliseconds}]"); return responsePacket; }
public void EnqueuePacket(CustomPacket pack, GameUser user) { lock (m_operLock) { m_operQueue.Enqueue(pack); m_loopEvent.Set(); } }
/// <summary> /// Functions searches previous scans and adds current scan there or if it can't tries to add it for today /// </summary> /// <param name="response"></param> /// <param name="techEntry"></param> /// <param name="sc"></param> /// <param name="dostawaEntry"></param> /// <returns></returns> public bool CheckBackOrAdd(CustomPacket response, Technical techEntry, ScannedCode sc, Dostawa dostawaEntry) { if (!SearchBack(techEntry, sc, dostawaEntry)) { return(AddOrCreateNewSet(response, techEntry, sc, dostawaEntry)); } return(true); }
void IPeer.OnPacket(byte[] buffer) { byte[] packetClone = new byte[1024]; Array.Copy(buffer, packetClone, buffer.Length); CustomPacket packet = new CustomPacket(packetClone, this); Program.mainGame.EnqueuePacket(packet, this); }
public void StartKeepAlive() { Timer keepAlive = new Timer((object e) => { CustomPacket packet = CustomPacket.Create(0); packet.Push(0); SendPacket(packet); }, null, 0, 3000); }
/// <summary> /// Functions searches previous scans and adds current scan there or if it can't tries to add it for today if scan wasn't complete according to delivery /// </summary> /// <param name="response"></param> /// <param name="techEntry"></param> /// <param name="sc"></param> /// <param name="dostawaEntry"></param> /// <returns></returns> public bool CheckBackOrAddQuantityIncorrect(CustomPacket response, Technical techEntry, ScannedCode sc, Dostawa dostawaEntry) { if (!SearchBack(techEntry, sc, dostawaEntry)) { var deliveriesForToday = _db.Dostawa.AsNoTracking().Include(c => c.Technical) .Where(c => c.Technical.Wiazka == sc.Wiazka && c.Data.Date == sc.dataDostawyOld.Date).ToList(); return(AddQuantityIncorrect(deliveriesForToday, response, techEntry, sc, dostawaEntry)); } return(true); }
/// <summary> /// Send a packet to every user of a list /// </summary> /// <param name="pck">Packet to send</param> /// <param name="userList">Users concerned</param> private void Broadcast(CustomPacket pck, UserList userList) { var users = userList.Users; foreach (var u in users) { TcpClient tmp = Server.TcpClients[u]; Net.sendMsg(tmp.GetStream(), pck); } }
/// <summary> /// Disconnecting user /// </summary> private void Disconnecting() { Server.TopicList.RemoveUserFromAll(_user); Server.ConnectedUsers.RemoveUser(_user); Server.TcpClients.Remove(_user); // Disconnect message CustomPacket pck = new CustomPacket(Operation.Reception, new InformationMessage(_user.Username + " is now offline")); Broadcast(pck, Server.ConnectedUsers); }
protected CustomPacket showMissing(CustomPacket packet) { using (var _db = new ZEMDBContext()) { CustomPacket response = new CustomPacket(FlagType.basic, HeaderTypes.basic, null, new List<string>(), null); VTInsertFunctions vTInsert = new VTInsertFunctions(_db, _log, null); string cutcode = packet.Args[0]; DateTime date = DateTime.Parse(packet.Args[1]); var techEntry = _db.Technical.FirstOrDefault(c => c.PrzewodCiety == cutcode); if (techEntry == null) { response.Flag = FlagType.notInTech; response.Header = HeaderTypes.error; return response; } else if (techEntry.KanBan) { response.Flag = FlagType.isKanban; response.Header = HeaderTypes.error; return response; } var wiazka = techEntry.Wiazka; var SetIDs = vTInsert.GetSetIDsForBundle(new ScannedCode { Wiazka = wiazka, dataDostawyOld = date }); if (SetIDs.Count() == 0) SetIDs.Add(0); List<string> missingCodes = new List<string>(); var deliveries = _db.Dostawa.AsNoTracking().Include(c => c.Technical).Where(c => c.Technical.Wiazka == wiazka && c.Data.Date == date.Date).ToList(); var scans = _db.VTMagazyn.AsNoTracking().Where(c => c.Wiazka == wiazka && c.DataDostawy.Date == date.Date).ToList(); foreach (int setNumber in SetIDs) { var codesForWiazka = _db.Technical.Where(c => c.Wiazka == wiazka && c.KanBan == false).Select(c => c.PrzewodCiety).ToList(); var scannedCodes = scans.Where(c => c.NumerKompletu == setNumber).Select(c => c.KodCiety).ToList(); if (scannedCodes.Count() == 0) { response.Flag = FlagType.nonScanned; response.Header = HeaderTypes.error; return response; } missingCodes.Add($"Brakujące kody dla wiązki {wiazka} komplet nr. {setNumber} po {vTInsert.GetPossibleDeclaredValue(new ScannedCode { kodCiety = cutcode, Wiazka = wiazka, dataDostawyOld = date }, scans, deliveries, setNumber)}"); missingCodes.AddRange(codesForWiazka.Except(scannedCodes).ToList()); } response.Args = missingCodes; return response; } }
public static void sendMsg(Stream s, CustomPacket pck) { BinaryFormatter bf = new BinaryFormatter(); try { bf.Serialize(s, pck); } catch (Exception ex) { throw ex; } }
/// <summary> /// Tries to add current scan as a whole /// </summary> /// <param name="response"></param> /// <param name="techEntry"></param> /// <param name="sc"></param> /// <param name="dostawaEntry"></param> /// <returns></returns> public bool AddOrCreateNewSet(CustomPacket response, Technical techEntry, ScannedCode sc, Dostawa dostawaEntry) { VTMagazyn VT = ExistsInVT(sc); if (VT == null && !sc.addedBefore) { // If no instance of this scan exists AddToVT(techEntry, sc, dostawaEntry); } else if (VT == null && sc.addedBefore) { if (sc.isForcedInsert) { // If instance of this code have been added to previous scans AddToVT(techEntry, sc, dostawaEntry); } else { response.Header = HeaderTypes.error; response.Flag = FlagType.codeExistsBack; return(false); } } else { if (sc.isForcedInsert) { var deliveriesForToday = _db.Dostawa.AsNoTracking().Include(c => c.Technical) .Where(c => c.Technical.Wiazka == sc.Wiazka && c.Data.Date == sc.dataDostawyOld.Date).ToList(); var VTList = new List <VTMagazyn>(); VTList.Add(VT); // If instance of this scan have been added for todays delivery if (VT.SztukiZeskanowane < GetPossibleDeclaredValue(sc, VTList, deliveriesForToday)) { return(AddQuantityIncorrect(deliveriesForToday, response, techEntry, sc, dostawaEntry)); } else { AddToVT(techEntry, sc, dostawaEntry, true); } } else { response.Header = HeaderTypes.error; response.Flag = FlagType.codeExists; return(false); } } return(true); }
private void missingCutCodeTextBox_KeyDown(object sender, KeyEventArgs e) { string inputCode = missingCutCodeTextBox.Text.Replace("PLC", "").Trim(); if (e.KeyCode == Keys.Enter && inputCode != "") { CustomPacket cp = new CustomPacket(FlagType.basic, HeaderTypes.basic, "showMissing", new List <string>(), null); cp.Args.Add(inputCode); cp.Args.Add(missingDateTimePicker.Value.ToShortDateString()); CustomPacket response = _client.SendReceiveMessage(cp); if (response.Header == HeaderTypes.error) { if (response.Flag == FlagType.notInTech) { MessageBox.Show("Nie znaleziono kodu w wykazie wiązek, sprawdź poprawność wpisanego kodu ciętego.", "Nie znaleziono", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } else if (response.Flag == FlagType.nonScanned) { MessageBox.Show("Żaden kod należący do tej wiązki nie był zeskanowany.", "Nie znaleziono", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } panel1.Controls.Clear(); int y = 0; foreach (var code in response.Args) { Label codeEntry = new Label(); codeEntry.Text = code; if (!code.StartsWith("Brakuj")) { codeEntry.Font = new Font("Microsoft Sans Serif", 16, FontStyle.Regular); codeEntry.Location = new Point(30, y); } else { codeEntry.Font = new Font("Microsoft Sans Serif", 20, FontStyle.Regular); codeEntry.Location = new Point(10, y); } codeEntry.AutoSize = true; y += 30; panel1.Controls.Add(codeEntry); } } }
/// <summary> /// Send data to server /// </summary> /// <param name="customPacket">Packet</param> private void Send(CustomPacket customPacket) { try { // Sending Net.sendMsg(Connection.GetStream(), customPacket); } catch (Exception) { // Fail if (Connection != null) { Console.Out.WriteLine("Connection error"); } } }
/// <summary> /// Send data to server /// </summary> /// <param name="customPacket">Packet</param> private void Send(CustomPacket customPacket) { try { // Sending Net.sendMsg(_connection.GetStream(), customPacket); } catch (Exception) { // Fail if (_connection != null) { MessageBox.Show("Connection with the server failed", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } }
/// <summary> /// Create topic /// </summary> /// <param name="customPacket">Packet received</param> /// <returns>Packet to send</returns> private CustomPacket CreateTopic(CustomPacket customPacket) { var t = (Topic)customPacket.Data; Server.TopicList.Semaphore.WaitOne(); if (Server.TopicList.SearchTopic(t) == null) { Server.TopicList.List.Add(t, new UserList()); Server.TopicList.Semaphore.Release(); return(new CustomPacket(Operation.Reception, new InformationMessage("Topic created"))); } else { Server.TopicList.Semaphore.Release(); return (new CustomPacket(Operation.Refused, new InformationMessage("Topic already existing"))); } }
protected CustomPacket getBin(CustomPacket packet) { using (var _db = new ZEMDBContext()) { CustomPacket response = new CustomPacket(FlagType.basic, HeaderTypes.basic, null, null, null); var bundle = _db.Technical.AsNoTracking().FirstOrDefault(c => c.PrzewodCiety == (string)packet.Payload).Wiazka; var BIN = _db.Technical.AsNoTracking().Where(c => c.Wiazka == bundle).Select(c => c.BIN).Distinct().ToList(); if (BIN == null) { response.Header = HeaderTypes.error; response.Flag = FlagType.binNotFound; } else { response.Args = BIN; } return response; } }
/// <summary> /// Handle chat inputs /// </summary> private void ChatInput() { // No more current user means that a logout happened while (CurrentUser != null) { CommandParser commandParser = new CommandParser(); CustomPacket customPacket = commandParser.ParseCommand(Console.In.ReadLine()); if (customPacket == null) { // Displaying errors Console.Out.WriteLine(commandParser.Message); } else { // Sending Send(customPacket); } } }
/// <summary> /// Create an user /// </summary> /// <param name="customPacket">Packet received</param> /// <returns>Packet to send</returns> private CustomPacket CreateUser(CustomPacket customPacket) { var u = (User)customPacket.Data; Server.AllUsers.Semaphore.WaitOne(); // We add the user if it does not already exists if (Server.AllUsers.SearchUser(u) == null) { Server.AllUsers.AddUser(u); Server.AllUsers.Semaphore.Release(); return(new CustomPacket(Operation.Reception, new InformationMessage("Account created"))); } else { Server.AllUsers.Semaphore.Release(); return (new CustomPacket(Operation.Refused, new InformationMessage("User already existing"))); } }
/// <summary> /// Send message to topic /// </summary> /// <param name="customPacket">Packet received</param> /// <returns>Packet to send</returns> private CustomPacket SendToTopic(CustomPacket customPacket) { Message msg = (Message)customPacket.Data; // Checking if user is connected to the topic if (Server.TopicList.CheckUserConnectionTopic((Topic)msg.Recipient, msg.Sender)) { // Sending the message to every user var users = Server.TopicList.List[(Topic)msg.Recipient]; CustomPacket pck = new CustomPacket(Operation.Reception, msg); Broadcast(pck, users); return(new CustomPacket(Operation.Reception, null)); } // If an error occured return(new CustomPacket(Operation.Refused, new InformationMessage("You are not connected to " + (Topic)msg.Recipient))); }