/// <summary> /// When new client is added /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public async void ClientAdded(object sender, EventArgs e) { var socket = ((CustomEventArgs)e).ClientSocket; var clientReader = new DataReader(socket.InputStream); clientReader.InputStreamOptions = InputStreamOptions.Partial; string clientName; while (true) { uint sizeFieldCount = await clientReader.LoadAsync(sizeof(uint)); if (sizeFieldCount != sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data. return; } uint bytesLength = clientReader.ReadUInt32(); uint actualBytesLength = await clientReader.LoadAsync(bytesLength); if (bytesLength != actualBytesLength) { // The underlying socket was closed before we were able to read the whole data. return; } var buffer = new byte[bytesLength]; clientReader.ReadBytes(buffer); clientName = Encoding.Unicode.GetString(buffer); var newClient = new ConnectedClient(clientName, socket); clients.Add(newClient); break; } OnClientConnected(socket, clientName); foreach (var client in clients) SendUsersList(client.Connection, client.UserName, clientName, ChatHelper.CONNECTED); var state = new ChatHelper.StateObject { InputStream = socket.InputStream }; var dataReader = new DataReader(socket.InputStream); var buff = new byte[dataReader.UnconsumedBufferLength]; dataReader.ReadBytes(buff); //ChatHelper.WriteToEventLog(Log.ClientConnected, EventLogEntryType.Information); }
/// <summary> /// When new client is added /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void ClientAdded(object sender, EventArgs e) { var socket = ((CustomEventArgs) e).ClientSocket; var bytes = new byte[1024]; var bytesRead = socket.Receive(bytes); var newUserName = Encoding.Unicode.GetString(bytes, 0, bytesRead); if (clients.Any(client => client.UserName == newUserName)) { SendNameAlreadyExist(socket,newUserName); return; } var newClient = new ConnectedClient(newUserName, socket); clients.Add(newClient); OnClientConnected(socket, newUserName); foreach (var client in clients) SendUsersList(client.Connection, client.UserName, newUserName, ChatHelper.CONNECTED); var state = new ChatHelper.StateObject { InputStream = socket }; socket.BeginReceive(state.Buffer, 0, ChatHelper.StateObject.BUFFER_SIZE, 0, OnReceive, state); ChatHelper.WriteToEventLog(Log.ClientConnected, EventLogEntryType.Information); }