public void RunClient() { TcpClient cliente; Protocol protocol = new Protocol(); User user; string clientTable = ""; string clientId; string clientNick; bool clientNumberFlag = false; bool clientNickNameflag = false; byte[] messageRcv = new byte[2048]; try { cliente = new TcpClient(); cliente.Connect(ip, Convert.ToInt32(port)); connection = cliente.Client; do { try { if (connection != null) { int received = connection.Receive(messageRcv); var data = new byte[received]; Array.Copy(messageRcv, data, received); if (received > 0) { //manda dados recebidos para serem separados e se retonar verdadeiro, trata if (protocol.unParseData(data)) { switch (protocol.opcode) { case 0x01: //verifica se veio do servidor if (protocol.idOrigin == 0xFF) { myID = protocol.idDestination[0]; if (connection != null) { //manda o nickname para o servidor connection.Send(protocol.parseData(0x01, myID, Enumerable.Repeat((byte)0x00, 8).ToArray(), Encoding.UTF8.GetBytes(txtBxNick.Text))); } } break; case 0x02: if (protocol.idOrigin == 0xFF) { clientTable = ""; clientUsers.Clear(); char[] messageChars = protocol.message.ToCharArray(); clientId = ""; clientNick = ""; //busca os caracteres e atualiza a tabela de usuários foreach (char c in messageChars) { if (c == ']') { clientNumberFlag = false; } else if (c == '}') { clientNickNameflag = false; clientTable += Environment.NewLine; user = new User(null, Convert.ToUInt16(clientId)); user.userSetNick(clientNick); clientUsers.Add(user); clientId = ""; clientNick = ""; } if (clientNumberFlag) { clientId += c; } if (clientNickNameflag) { clientNick += c; } if (c == '[') { clientNumberFlag = true; } else if (c == '{') { clientNickNameflag = true; clientTable += " "; } else if (c != ']' && c != '}') { clientTable += c; } } sendToUsersBox("", clientTable); } break; case 0x03: if (protocol.idOrigin == 0xFF) { sendToChatBox("Append", "Server: " + protocol.message.Replace("\0", string.Empty)); } else { sendToChatBox("Append", clientUsers.Find(c => c.userGetID() == protocol.idOrigin).userGetNick() + ": " + protocol.message.Replace("\0", string.Empty)); } break; } } } messageRcv = new byte[2048]; } } catch (Exception) { Environment.Exit(Environment.ExitCode); } } while (true); } catch (Exception error) { MessageBox.Show(error.ToString()); } }
private void ReceiveCallback(IAsyncResult AR) { Socket current = (Socket)AR.AsyncState; Protocol protocol = new Protocol(); User localUser; int received; try { received = current.EndReceive(AR); } catch (SocketException) { sendToChatBox("Append", "Cliente desconectado " + current.RemoteEndPoint.ToString()); // Don't shutdown because the socket may be disposed and its disconnected anyway. current.Close(); //procura o usuário cujo socket é igual ao que está sendo finalizado if (clientUsers.Count > 0) { clientUsers.Remove(clientUsers.Find(x => x.socket == current)); clientSockets.Remove(current); updateClientTable(); } return; } byte[] recBuf = new byte[received]; Array.Copy(buffer, recBuf, received); /* * Aqui vai uma função que deve separar a mensagem e trata-la de acordo com os usuarios recebidos */ if (protocol.unParseData(recBuf)) { switch (protocol.opcode) { case 0x01: for (int count = 0; count < clientUsers.Count; count++) { if (clientUsers[count].userGetID() == Convert.ToByte(protocol.idOrigin)) { clientUsers[count].userSetNick(protocol.message.Replace("\0", string.Empty)); //setou o nick name corretamente, agora precisa mandar a tabela atualizada para todos os clientes updateClientTable(); break; } } break; case 0x02: break; case 0x03: for (uint count = 0; count < 8; count++) { if (clientUsers.Count > count) { localUser = clientUsers.Find(client => client.userGetID() == protocol.idDestination[count]); if (localUser != null && localUser.socket.Connected) { localUser.socket.Send(protocol.parseData(0x03, protocol.idOrigin, protocol.idDestination, Encoding.UTF8.GetBytes(protocol.message))); } } } sendToChatBox("Append", clientUsers.Find(c => c.userGetID() == protocol.idOrigin).userGetNick() + ": " + protocol.message.Replace("\0", string.Empty)); break; } } current.BeginReceive(buffer, 0, 2048, SocketFlags.None, ReceiveCallback, current); }