Skip to content

Commit

Permalink
Fixed wrong lobby ID returned & stream-locking
Browse files Browse the repository at this point in the history
  • Loading branch information
rackover committed Jun 14, 2020
1 parent b8cf897 commit c730955
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 11 deletions.
13 changes: 8 additions & 5 deletions Broadcast/Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ public Server()
try {
// BLOCKing
var msgBuffer = ns.Read();
if (msgBuffer.Length == 0) continue;
if (client.Available <= 0 && msgBuffer.Length == 0) {
break;
}

var messageType = msgBuffer[0];
byte[] deserializable = new byte[msgBuffer.Length - 1];
Expand Down Expand Up @@ -85,7 +87,8 @@ public Server()
throw new TaskCanceledException();
}
}
client.Dispose();
ns.Dispose();
client.Close();
logger.Info("Client ["+clientId+"] is no longer connected (EXIT)");
}).Start();

Expand Down Expand Up @@ -188,10 +191,9 @@ void HandleSubmit(byte[] deserializable, TcpClient client, uint clientId)

lastHeardAbout[lobby] = DateTime.UtcNow;
var id = BitConverter.GetBytes(uIntId);
Array.Reverse(id);
client.GetStream().WriteData(id); // I return the ID of the lobby

logger.Info("Finished processing lobby submission from client [{0}]!".Format(clientId));
logger.Info("Finished processing lobby submission from client [{0}] (gave them ID {1} for their lobby)!".Format(clientId, uIntId));
}

void HandleDelete(byte[] deserializable, TcpClient client, uint clientId)
Expand All @@ -200,7 +202,8 @@ void HandleDelete(byte[] deserializable, TcpClient client, uint clientId)

var targetLobby = BitConverter.ToUInt32(deserializable, 0);
lock (lobbies) {
lobbies.RemoveAll(o => o.id == targetLobby);
var removed = lobbies.RemoveAll(o => o.id == targetLobby);
logger.Debug("Removed {1} lobbies (every lobby with ID {2}) as requested by client [{0}]".Format(clientId, removed, targetLobby)) ;
}
logger.Info("Finished removing lobby {1} as requested by client [{0}]".Format(clientId, targetLobby));
}
Expand Down
14 changes: 11 additions & 3 deletions BroadcastClient/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,17 @@ void Start()
{
if (client!= null) {
logger.Debug("Disposing previous client");
client.Dispose();
try {
client.GetStream().Dispose();
}
catch(InvalidOperationException) {
// Nothing to do
}
client.Close();
}
logger.Debug("Instantiating a new client");
client = new TcpClient(address.ToString(), Networking.PORT);
logger.Debug("Done! Setting receivetimeout...");
logger.Debug("Done! Setting receive timeout...");
client.ReceiveTimeout = SECONDS_BEFORE_EMPTY_READ * 1000;
logger.Debug("Set client ReceiveTimeout to " + (SECONDS_BEFORE_EMPTY_READ * 1000)+"ms");
logger.Info("Client connected to "+address+":"+Networking.PORT);
Expand Down Expand Up @@ -200,17 +206,19 @@ bool ConnectIfNotConnected()
}
}

public bool IsConnected()
bool IsConnected()
{
if (client != null && client.Connected) {
try {

NetworkStream stream = client.GetStream();
List<byte> message = new List<byte>();
message.Add(Networking.PROTOCOL_HELLO);
message.AddRange(Encoding.UTF8.GetBytes("Oh hey!"));
stream.WriteData(message.ToArray());

var data = stream.Read();

if (data.Length > 0) {
return true;
}
Expand Down
45 changes: 43 additions & 2 deletions BroadcastShared/Networking.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Net.Sockets;
using System.Text;
using System.Linq;
using System.Threading.Tasks;

namespace Broadcast.Shared
{
Expand All @@ -23,6 +24,33 @@ public MessageBuildingException(string msg, byte[] constructed) : base(msg + "\n
public const byte VERSION = 5;


static Dictionary<NetworkStream, bool> isStreamBusy = new Dictionary<NetworkStream, bool>();

static bool IsStreamBusy(this NetworkStream stream)
{
if (!isStreamBusy.ContainsKey(stream)) {
isStreamBusy.Add(stream, false);
}
return isStreamBusy[stream];
}

static void Lock(this NetworkStream stream)
{
isStreamBusy[stream] = true;
}

static void Unlock(this NetworkStream stream)
{
isStreamBusy[stream] = false;
}

static void WaitForStreamAvailability(this NetworkStream stream)
{
while (IsStreamBusy(stream)) {
Task.WaitAny(Task.Delay(10));
}
}

public static void WriteData(this NetworkStream stream, byte[] data)
{
var size = BitConverter.GetBytes(Convert.ToUInt32(data.Length));
Expand All @@ -32,16 +60,26 @@ public static void WriteData(this NetworkStream stream, byte[] data)
responseList.AddRange(data);
var toWrite = responseList.ToArray();

stream.WaitForStreamAvailability();
stream.Lock();

stream.Write(toWrite, 0, toWrite.Length);

stream.Unlock();
}

public static byte[] Read(this NetworkStream stream)
{
int bites = 0;
byte[] sizeBuffer = new byte[4]; // UINT32 is 4 bytes
stream.Read(sizeBuffer, 0, sizeBuffer.Length);

stream.WaitForStreamAvailability();
stream.Lock();

stream.Read(sizeBuffer, 0, sizeBuffer.Length);

var length = BitConverter.ToUInt32(sizeBuffer, 0);
if (length == 0) return new byte[0]; // Garbage

// Emptying network buffer from data
var remainingData = Convert.ToInt64(length);
Expand All @@ -56,9 +94,12 @@ public static byte[] Read(this NetworkStream stream)
Array.Copy(buffer, shrankArray, shrankArray.Length);

data.AddRange(shrankArray);
bites++;
bites++;
}

stream.Unlock();


// Concatenate data
var msgBuffer = data.ToArray();
if (msgBuffer.Length != length) {
Expand Down
2 changes: 1 addition & 1 deletion BroadcastTester/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ static void Main(string[] args)
new Task(delegate {
new Server.Server();
}).Start();
new Client.Client("localhost", "test").Test();
new Client.Client("localhost", "test", true).Test();
}
}
}

0 comments on commit c730955

Please sign in to comment.