C
C#ā€¢10mo ago
zoon_

Clients list

I want to make a clients list for online clients connected to a server in my winform socket app
1694 Replies
zoon_
zoon_OPā€¢10mo ago
the approach i thought of was to send a list of client names to each client socket and in my client class that has the socket i receive it and append each string from that list to my client text box but i dont know how to send/receive a List. or Collection to begin with any ideas ? i will send my code just in case $bin
leowest
leowestā€¢10mo ago
$paste
MODiX
MODiXā€¢10mo ago
If your code is too long, you can post to https://paste.mod.gg/ and copy the link into chat for others to see your shared code!
leowest
leowestā€¢10mo ago
how are u sending packets do u have a way to identify it? because the way I see it... When client A connects it should get a list of all current connected users from there u can just send who is connecting/disconnecting instead of a full list every time
zoon_
zoon_OPā€¢10mo ago
okay hold on ill send my current code
zoon_
zoon_OPā€¢10mo ago
BlazeBin - ujwtsafxtvji
A tool for sharing your source code with the world!
zoon_
zoon_OPā€¢10mo ago
here this is what i got so far the idea of having a list of online clients and each time a new client connects i tell the server and the server sends his name and in the client.cs i store the name in my list and append it to the clientslist text box
zoon_
zoon_OPā€¢10mo ago
for some reason this happens
No description
zoon_
zoon_OPā€¢10mo ago
it sends USERJOINED in the chatbox and doesnt even show the names in the client list hmm i just saw that the server receives "USERNAME|zoonUSERJOINED|zoon" lmao maybe its bc of those lines
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (TB_PortNumber.Text is not "" && TB_Username.Text is not "" && TB_Username.Text is not "")
{
endPoint = new IPEndPoint(IPAddress.Parse(TB_HostAddress.Text), int.Parse(TB_PortNumber.Text));
clientSocket.Connect(endPoint);
clientSocket.Send(Encoding.Unicode.GetBytes($"USERNAME|{TB_Username.Text}"));
if (Utility.SocketConnected(clientSocket))
{
LB_connectionStatus.Text = "Connected";
clientSocket.Send(Encoding.Unicode.GetBytes($"USERJOINED|{TB_Username.Text}"));
Thread readingThread = new Thread(ReadIncomingData) { IsBackground = true };
readingThread.Start();
}
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (TB_PortNumber.Text is not "" && TB_Username.Text is not "" && TB_Username.Text is not "")
{
endPoint = new IPEndPoint(IPAddress.Parse(TB_HostAddress.Text), int.Parse(TB_PortNumber.Text));
clientSocket.Connect(endPoint);
clientSocket.Send(Encoding.Unicode.GetBytes($"USERNAME|{TB_Username.Text}"));
if (Utility.SocketConnected(clientSocket))
{
LB_connectionStatus.Text = "Connected";
clientSocket.Send(Encoding.Unicode.GetBytes($"USERJOINED|{TB_Username.Text}"));
Thread readingThread = new Thread(ReadIncomingData) { IsBackground = true };
readingThread.Start();
}
leowest
leowestā€¢10mo ago
for a start I would suggest u change how you're sending messages in a more structured format that u can track
zoon_
zoon_OPā€¢10mo ago
hm ? how so
leowest
leowestā€¢10mo ago
USERNAME|zoonUSERJOINED|zoon
USERNAME|zoonUSERJOINED|zoon
your code would split this as:
USERNAME
zoonUSERJOINED
zoon
USERNAME
zoonUSERJOINED
zoon
so u would have 0, 1, 2
zoon_
zoon_OPā€¢10mo ago
i dont even know why it is sending two messages at the same time lmao
leowest
leowestā€¢10mo ago
so you're essentially losing data even if that was not intended u can see 1 issue
zoon_
zoon_OPā€¢10mo ago
its supposed to send ONE and execute it and then send the other one
leowest
leowestā€¢10mo ago
now say you send a message that is bigger than 1024 it will break into 2 messages
zoon_
zoon_OPā€¢10mo ago
yeah true
leowest
leowestā€¢10mo ago
so start by solving that by structuring a format u can recognize
zoon_
zoon_OPā€¢10mo ago
well i like that format code|<insertmessage> but i guess it doesnt work well what kind of format do u suggest
leowest
leowestā€¢10mo ago
size opcode data this is the most primitive way that its usually done
zoon_
zoon_OPā€¢10mo ago
hmmm soo if i do it by opcode i can be like
leowest
leowestā€¢10mo ago
so u know the size of the message, opcode is usually a command
zoon_
zoon_OPā€¢10mo ago
MESSAGE : 1 USERNAME: 0 etc ?
leowest
leowestā€¢10mo ago
and data would be whatever the command needs to use yes it could be a simple list of enums
zoon_
zoon_OPā€¢10mo ago
enum OpCode
{
MESSAGE= 0,
USERNAME= 1,
UPDATELIST= 2
}
enum OpCode
{
MESSAGE= 0,
USERNAME= 1,
UPDATELIST= 2
}
like that ?
leowest
leowestā€¢10mo ago
sure could be that
zoon_
zoon_OPā€¢10mo ago
am i supposed to put that in like the message class or what where am i supposed t o put that can i put it in my utility.cs ?
leowest
leowestā€¢10mo ago
I dont see any message class in your code to know what it does
zoon_
zoon_OPā€¢10mo ago
it does nothing im not even using it
leowest
leowestā€¢10mo ago
anyway the message would be send as bytes so it would need to be structured as such size opcode data so for example
zoon_
zoon_OPā€¢10mo ago
yes ?
leowest
leowestā€¢10mo ago
give me a moment busy with other stuff
zoon_
zoon_OPā€¢10mo ago
okay tyt
leowest
leowestā€¢10mo ago
sorry things just got dropped at once
zoon_
zoon_OPā€¢10mo ago
its okay take your time im playing anyw and tired
leowest
leowestā€¢10mo ago
so you could have a class called Message for example, its just for simplicity, trying to do this as simple as possible to explain to you the idea
zoon_
zoon_OPā€¢10mo ago
this shit frustrates me
leowest
leowestā€¢10mo ago
public class MessageData
{
public Header Header { get; set; }
public string Message { get; set; }
}
public class MessageData
{
public Header Header { get; set; }
public string Message { get; set; }
}
zoon_
zoon_OPā€¢10mo ago
i dont know how to pass objects
leowest
leowestā€¢10mo ago
Ah but how would I send that, we would use a combination of memorystream and binarywriter to convert it to bytes
zoon_
zoon_OPā€¢10mo ago
i tried using a json serializer it bugged so hard
leowest
leowestā€¢10mo ago
and send the bytes
var msg = new MessageData
{
Header = Header.MESSAGE,
Message = "sending some test data..."
};
SendMessage(msg);
var msg = new MessageData
{
Header = Header.MESSAGE,
Message = "sending some test data..."
};
SendMessage(msg);
zoon_
zoon_OPā€¢10mo ago
alright ill try that
leowest
leowestā€¢10mo ago
and here is where the magic happens
zoon_
zoon_OPā€¢10mo ago
i see i see ill try that so basically i make a class messageData that has an enum type for opcode and the message that im sending which is the data ? and i send it and receive it with different headers etc
leowest
leowestā€¢10mo ago
public int SendMessage(MessageData data)
{
// placeholder to have the byte array to fill after
var size = 0;
// here we creante a memorystream to store the bytes
using var ms = new MemoryStream();
// here we use BinaryWriter for the convenience of converting types to bytes
// we also set the encoding for strings
using var bw = new BinaryWriter(ms, Encoding.UTF8);
// write the size to the buffer
bw.Write(size);
// write the header to the buffer
bw.Write((short)data.Header);
// write the message to the buffer
bw.Write(data.Message);
// go back to the begin of the stream
bw.Seek(0, SeekOrigin.Begin);
// update the size with the actual size we have now.
bw.Write((int)packetWriter.BaseStream.Length);
// send the buffer using the socket
return Send(ms.ToArray());
}
public int SendMessage(MessageData data)
{
// placeholder to have the byte array to fill after
var size = 0;
// here we creante a memorystream to store the bytes
using var ms = new MemoryStream();
// here we use BinaryWriter for the convenience of converting types to bytes
// we also set the encoding for strings
using var bw = new BinaryWriter(ms, Encoding.UTF8);
// write the size to the buffer
bw.Write(size);
// write the header to the buffer
bw.Write((short)data.Header);
// write the message to the buffer
bw.Write(data.Message);
// go back to the begin of the stream
bw.Seek(0, SeekOrigin.Begin);
// update the size with the actual size we have now.
bw.Write((int)packetWriter.BaseStream.Length);
// send the buffer using the socket
return Send(ms.ToArray());
}
ms.ToArray() generates something like this
20 00 00 00 00 00 19 73 65 6E 64 69 6E 67 20 73 6F 6D 65 20 74 65 73 74 20 64 61 74 61 2E 2E 2E
20 00 00 00 00 00 19 73 65 6E 64 69 6E 67 20 73 6F 6D 65 20 74 65 73 74 20 64 61 74 61 2E 2E 2E
and if we break it down we have
message size
20 00 00 00
header
00 00
message
19 73 65 6E 64 69 6E 67 20 73 6F 6D 65 20 74 65 73 74 20 64 61 74 61 2E 2E 2E
message size
20 00 00 00
header
00 00
message
19 73 65 6E 64 69 6E 67 20 73 6F 6D 65 20 74 65 73 74 20 64 61 74 61 2E 2E 2E
these are hexadecimals representation 20 00 00 00 is 32 our header is Message which is 0, so 00 00 ah but why 32 is 20 00 00 00 because int is 4 bytes long why header is 00 00 because short 2 bytes long so its a bit confusing because you have to understand the types and how they work.
zoon_
zoon_OPā€¢10mo ago
holy shit šŸ’€ that is alot
leowest
leowestā€¢10mo ago
yes it is, there are many ways to do this and this is the simplest to learn imo if you use signalr or an already made library u cut all this but u also dont learn the underlying of how it works
zoon_
zoon_OPā€¢10mo ago
alright ill check this out
leowest
leowestā€¢10mo ago
the key here is that now every message u send start with a size so u always know how much U need to read until u read the next message so now this
byte[] buffer = new byte[1024];
int bytesRead = 0;
do
{
if (Utility.SocketConnected(client.Socket))
{
bytesRead = client.Socket.Receive(buffer);
string[] messageReceived = Encoding.Unicode.GetString(buffer, 0, bytesRead).Split('|');
switch (messageReceived[0])
{
case "MESSAGE":
BroadcastMessage(client, $"({client.Name}) sent: {messageReceived[1]}");
break;
case "USERNAME":
client.Name = messageReceived[1];
break;
case "USERJOINED":
AddOnlineClient(messageReceived[1]);
break;
default:
MessageBox.Show("Something went wrong..");
break;
}
}
else
BroadcastMessage(client, $"({client.Name}) Has disconnected");

} while (bytesRead > 0);
byte[] buffer = new byte[1024];
int bytesRead = 0;
do
{
if (Utility.SocketConnected(client.Socket))
{
bytesRead = client.Socket.Receive(buffer);
string[] messageReceived = Encoding.Unicode.GetString(buffer, 0, bytesRead).Split('|');
switch (messageReceived[0])
{
case "MESSAGE":
BroadcastMessage(client, $"({client.Name}) sent: {messageReceived[1]}");
break;
case "USERNAME":
client.Name = messageReceived[1];
break;
case "USERJOINED":
AddOnlineClient(messageReceived[1]);
break;
default:
MessageBox.Show("Something went wrong..");
break;
}
}
else
BroadcastMessage(client, $"({client.Name}) Has disconnected");

} while (bytesRead > 0);
which is in your code, would become something like this
do
{
if (Utility.SocketConnected(client.Socket))
{
var sizeBuffer = new byte[4];
var receivedBytes = client.Socket.Receive(sizeBuffer);
if (receivedBytes != sizeBuffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");

// Need logic to read the buffer until u get size inside buffer
var size = BitConverter.ToInt32(sizeBuffer, 0);
var buffer = new byte[size];
receivedBytes = client.Socket.Receive(buffer);
if (receivedBytes != buffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");

using var ms = new MemoryStream(buffer);
using var br = new BinaryReader(incomingPacketStream);
var header = (Header)br.ReadInt16();

switch (header)
{
case Header.MESSAGE:
string messageReceived = br.ReadString();
BroadcastMessage(client, $"({client.Name}) sent: {messageReceived[1]}");
break;
case Header.USERNAME:
break;
case Header.USERJOINED:
break;
default:
MessageBox.Show("Something went wrong..");
break;
}
}
else
BroadcastMessage(client, $"({client.Name}) Has disconnected");

} while (bytesRead > 0);
do
{
if (Utility.SocketConnected(client.Socket))
{
var sizeBuffer = new byte[4];
var receivedBytes = client.Socket.Receive(sizeBuffer);
if (receivedBytes != sizeBuffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");

// Need logic to read the buffer until u get size inside buffer
var size = BitConverter.ToInt32(sizeBuffer, 0);
var buffer = new byte[size];
receivedBytes = client.Socket.Receive(buffer);
if (receivedBytes != buffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");

using var ms = new MemoryStream(buffer);
using var br = new BinaryReader(incomingPacketStream);
var header = (Header)br.ReadInt16();

switch (header)
{
case Header.MESSAGE:
string messageReceived = br.ReadString();
BroadcastMessage(client, $"({client.Name}) sent: {messageReceived[1]}");
break;
case Header.USERNAME:
break;
case Header.USERJOINED:
break;
default:
MessageBox.Show("Something went wrong..");
break;
}
}
else
BroadcastMessage(client, $"({client.Name}) Has disconnected");

} while (bytesRead > 0);
this is not working code its just hypothetical so u can understand the idea behind it. at the top u read the size, if the length is right u move to reading the MessageData
zoon_
zoon_OPā€¢10mo ago
but each message wont be the same size so it wont necessarily match the whole buffer size yk ?
leowest
leowestā€¢10mo ago
that's why u read the size of the message first do u see that i read the size
zoon_
zoon_OPā€¢10mo ago
var receivedBytes = client.Socket.Receive(sizeBuffer); if (receivedBytes != sizeBuffer.Length) throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}."); im talking ab this
leowest
leowestā€¢10mo ago
then I create a buffer with the appropriate size
zoon_
zoon_OPā€¢10mo ago
ah i see
leowest
leowestā€¢10mo ago
yes the first one is reading just the size whic his 4 bytes int = 4 bytes then once we have the size we read the whole message
zoon_
zoon_OPā€¢10mo ago
I SEEE alrightt let me try
leowest
leowestā€¢10mo ago
so I only left out 1 thing for u to figure out the logic to read the full buffer for the MessageData try to send big messages so it will break the message into multiple packets its not complicate u just need a loop that will count until u have buffer.Length == size then u, use Read to append the next chunk of information in the right position in the buffer so u need to keep track of how much was written and how much is left to read but for small message it will work just fine without needing to do that anyway gl šŸ˜‰
zoon_
zoon_OPā€¢10mo ago
šŸ˜­ thank you let me try
leowest
leowestā€¢10mo ago
maybe u should write a separated console project and do it there just so u understand the idea before u integrate it all
zoon_
zoon_OPā€¢9mo ago
i think after getting familiar with this ill also change how my app structured i have client and server both in 1 project ill make separate projects under 1 solution
leowest
leowestā€¢9mo ago
u can also make a common library with say the MessageData that both share etc u could even make the socket shareable in there too if u want
zoon_
zoon_OPā€¢9mo ago
i do not know what a common library is u mena like .h in c++ ? header file ?
leowest
leowestā€¢9mo ago
no a c# class library create one then put your MessageData class there remove it from the other projects then u add the class library as project reference
zoon_
zoon_OPā€¢9mo ago
let me try that ill first setup the project server and client
zoon_
zoon_OPā€¢9mo ago
using the new binary serializer is this called like binary serializer or memory stream ? so i can look it up on youtube
leowest
leowestā€¢9mo ago
that is neither it just helps u write stuff in binary with proper encoding etc and primitive types to bytes
zoon_
zoon_OPā€¢9mo ago
so im basically writing my data in binary so i can send it over sockets
leowest
leowestā€¢9mo ago
yep
zoon_
zoon_OPā€¢9mo ago
we are going beyond low level šŸ˜„
leowest
leowestā€¢9mo ago
its not low level thou in terms of code
zoon_
zoon_OPā€¢9mo ago
yeah i know in terms of logic i mean
leowest
leowestā€¢9mo ago
but yeah if u want to read the files your self u would need to use a hex editor
zoon_
zoon_OPā€¢9mo ago
this seems too advanced
leowest
leowestā€¢9mo ago
and have some understanding of types
zoon_
zoon_OPā€¢9mo ago
yea
leowest
leowestā€¢9mo ago
but all data is sent as bytes so understanding how it works imo is good
zoon_
zoon_OPā€¢9mo ago
true oaky let me get to work
leowest
leowestā€¢9mo ago
that also helps u understand how u can serialize and send serialized data further u go in because now u understand u need a certain structure and u need to know where it start and where it ends and have means to properly read it to that extent which those libraries do it all for u šŸ˜›
zoon_
zoon_OPā€¢9mo ago
yeah i see that signalR does everything and im basically trying to reimplement a whole library
leowest
leowestā€¢9mo ago
not the whole library like 5% of it
zoon_
zoon_OPā€¢9mo ago
enough to make myself proud
leowest
leowestā€¢9mo ago
it does a lot more than just that
zoon_
zoon_OPā€¢9mo ago
how do i make reference for projects make two projects communicate
leowest
leowestā€¢9mo ago
u right click reference in the project u want to reference it and add project as reference
zoon_
zoon_OPā€¢9mo ago
the server should have reference of the client right ? not the other way around
leowest
leowestā€¢9mo ago
no neither server nor client need to reference each other
zoon_
zoon_OPā€¢9mo ago
oohhh nvm nvm yeah ur right
leowest
leowestā€¢9mo ago
unless you're writing a class on top of socket class that can be used by both server and client which at that point u would have a class library that owuld hold that class and both projects would reference from it
zoon_
zoon_OPā€¢9mo ago
yea
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
so the common is a common library
leowest
leowestā€¢9mo ago
just as an example
zoon_
zoon_OPā€¢9mo ago
that holds classes that are shared between client and server ?
leowest
leowestā€¢9mo ago
yes ActionType is the enum ClientMessage is the data sent
zoon_
zoon_OPā€¢9mo ago
i see so instead of having enum OpCOde{} in each the client and the server i just make it once in the common library and use it
leowest
leowestā€¢9mo ago
sure
zoon_
zoon_OPā€¢9mo ago
though ill make multiple enums since both wont have the same opcodes or atleast the function behind them
leowest
leowestā€¢9mo ago
I mean if both use the exact same thing yeah
zoon_
zoon_OPā€¢9mo ago
i need to familiarize myself with async await
zoon_
zoon_OPā€¢9mo ago
No description
No description
zoon_
zoon_OPā€¢9mo ago
like this ?
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
well if you client and server have different actions u would have 2 different enums
zoon_
zoon_OPā€¢9mo ago
yeah like this ? or do u mean different actiontypes
leowest
leowestā€¢9mo ago
public enum ActionType : short
{
Connected,
Username,
Message,
PrivateMessage,
UpdateList,
Disconnected
}
public enum ActionType : short
{
Connected,
Username,
Message,
PrivateMessage,
UpdateList,
Disconnected
}
mine is just this for both
zoon_
zoon_OPā€¢9mo ago
i see well i guess both would work : short what is this for
leowest
leowestā€¢9mo ago
even thou I might not use some of the enum for the client to define the underlying type of the enum so it will be 2 bytes and use less space by default an enum is an int
zoon_
zoon_OPā€¢9mo ago
i see okay ill use this then
leowest
leowestā€¢9mo ago
its very rare that u might need more than 65K+ enums could have been a byte too
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
fair fair and in the project ref i add ref to this library ?
leowest
leowestā€¢9mo ago
huh?
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
yes i add the communicator to both the client and the server ?
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
bw.Write((int)packetWriter.BaseStream.Length); what does this do ? what is the packetwriter and basestream ?
leowest
leowestā€¢9mo ago
basestream takes the underlying type stream in order to access its Length so its basically updating the size of the packet to the first 4 bytes that's why it does 0, seek origin its returning to the begin of the stream
zoon_
zoon_OPā€¢9mo ago
yeah its returning so it updates the first few bytes that translate to the size
leowest
leowestā€¢9mo ago
we first write 0 to size because we dont know the size yet until it finishes writing to the stream so once the stream is filled we have the size and just update it its to avoid having to turn everything into bytes just for the sake of knowing the size instead of just writing it and updating it after
zoon_
zoon_OPā€¢9mo ago
how do i use the library i created after i added reference to it through the using ?
leowest
leowestā€¢9mo ago
using Comunicator;
zoon_
zoon_OPā€¢9mo ago
alrighty
leowest
leowestā€¢9mo ago
my bad I forgot to say u need to - sizeof(int) to exclude the first 4 bytes that u read as a header of the size bw.Write((int)packetWriter.BaseStream.Length - sizeof(int));
zoon_
zoon_OPā€¢9mo ago
wdym as a header of the size ?
leowest
leowestā€¢9mo ago
var sizeBuffer = new byte[sizeof(int)];
var receivedBytes = client.Socket.Receive(sizeBuffer);
if (receivedBytes != sizeBuffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");
var sizeBuffer = new byte[sizeof(int)];
var receivedBytes = client.Socket.Receive(sizeBuffer);
if (receivedBytes != sizeBuffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");
when it does that it removes 4 bytes from the buffer and now it know the size of the rest
zoon_
zoon_OPā€¢9mo ago
all of this just writes the type to bytes am i correct ?
No description
leowest
leowestā€¢9mo ago
so its total - 4
zoon_
zoon_OPā€¢9mo ago
and it saves it in the bw ?
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
what does the description says
zoon_
zoon_OPā€¢9mo ago
it updates the size
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
to the actual message size
leowest
leowestā€¢9mo ago
so it updats that with the size of the buffer so it includes everything but the message is read separated from teh size u read the size then u read the message right?
zoon_
zoon_OPā€¢9mo ago
yea
leowest
leowestā€¢9mo ago
then u have to - sizeof(int) imagine your message size is 20 + the size = 24 what happens if
zoon_
zoon_OPā€¢9mo ago
so in the buffer i should only store the message not the size ?
leowest
leowestā€¢9mo ago
var size = BitConverter.ToInt32(sizeBuffer, 0);
var buffer = new byte[size];
receivedBytes = client.Socket.Receive(buffer);
if (receivedBytes != buffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");
var size = BitConverter.ToInt32(sizeBuffer, 0);
var buffer = new byte[size];
receivedBytes = client.Socket.Receive(buffer);
if (receivedBytes != buffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");
zoon_
zoon_OPā€¢9mo ago
or the type
leowest
leowestā€¢9mo ago
size there is 24 no, you just have to -4 the total size because then u have the actual size of the message excluding the size
zoon_
zoon_OPā€¢9mo ago
i see so those 4 bytes im excluding are the Size bytes
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
but why do i even want to know the size if im not gonna send it lmao
leowest
leowestā€¢9mo ago
20 00 00 00 00 00 19 73 65 6E 64 69 6E 67 20 73 6F 6D 65 20 74 65 73 74 20 64 61 74 61 2E 2E 2E
^^ ^^ ^^ ^^ size
20 00 00 00 00 00 19 73 65 6E 64 69 6E 67 20 73 6F 6D 65 20 74 65 73 74 20 64 61 74 61 2E 2E 2E
^^ ^^ ^^ ^^ size
that size represents the rest of the data if it includes itself in the size then u have an array exception
zoon_
zoon_OPā€¢9mo ago
hold on
leowest
leowestā€¢9mo ago
ofc you send the size wdym
zoon_
zoon_OPā€¢9mo ago
.
leowest
leowestā€¢9mo ago
how do u think u know how much to read
zoon_
zoon_OPā€¢9mo ago
. let me keep this here
leowest
leowestā€¢9mo ago
so let me go with an easier example
zoon_
zoon_OPā€¢9mo ago
here when i write the size for the first time
No description
zoon_
zoon_OPā€¢9mo ago
its 00 00 00 00 right ?
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
then when i write the data.message which is the message itself right ? i go back to the start of the byte array. and write the actual size of the message but how did i know the size of the message ? thats what i dont understand
leowest
leowestā€¢9mo ago
then u write the actiontype and then the data.message
MODiX
MODiXā€¢9mo ago
leowest
Quoted by
<@1102729783969861782> from #Clients list (click here)
From leowest
React with āŒ to remove this embed.
leowest
leowestā€¢9mo ago
because of this
zoon_
zoon_OPā€¢9mo ago
does this return the length of what i wrote in the byte array till now ?
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
okay but then i also wrote the first 4 bytes of the size
leowest
leowestā€¢9mo ago
Seek makes it go back to the position 0 of the byte array
zoon_
zoon_OPā€¢9mo ago
if i can do that to get the whole length of the message. why do i need the first four bytes ?
leowest
leowestā€¢9mo ago
so what happens if u go back to 0 and write it will write on top of what already exists in the byte array
zoon_
zoon_OPā€¢9mo ago
yes
leowest
leowestā€¢9mo ago
so it updates 00 00 00 00 to actual size i.e.: 20 00 00 00
zoon_
zoon_OPā€¢9mo ago
but that 20 also includes size + actiontype + message right ?
leowest
leowestā€¢9mo ago
but this 20 00 00 00 is the entire thing and u only want actiontype + message so you remove sizeof(int) which is 4 yes
zoon_
zoon_OPā€¢9mo ago
okay i understand BUT if i can just get the length of what i wrote why do i need the size parameter that tells me the actiontype + message size
leowest
leowestā€¢9mo ago
because how do the client know that?
zoon_
zoon_OPā€¢9mo ago
why cant i just write the actiontype + message and i get the length
leowest
leowestā€¢9mo ago
if u just send actiontype and message how do u know the size
zoon_
zoon_OPā€¢9mo ago
public int SendMessage(MessageData data)
{
// here we creante a memorystream to store the bytes
using var ms = new MemoryStream();
// here we use BinaryWriter for the convenience of converting types to bytes
// we also set the encoding for strings
using var bw = new BinaryWriter(ms, Encoding.UTF8);
// write the header to the buffer
bw.Write((short)data.Header);
// write the message to the buffer
bw.Write(data.Message);
// go back to the begin of the stream
bw.Seek(0, SeekOrigin.Begin);
// update the size with the actual size we have now.
bw.Write((int)packetWriter.BaseStream.Length);
// send the buffer using the socket
return Send(ms.ToArray());
}
public int SendMessage(MessageData data)
{
// here we creante a memorystream to store the bytes
using var ms = new MemoryStream();
// here we use BinaryWriter for the convenience of converting types to bytes
// we also set the encoding for strings
using var bw = new BinaryWriter(ms, Encoding.UTF8);
// write the header to the buffer
bw.Write((short)data.Header);
// write the message to the buffer
bw.Write(data.Message);
// go back to the begin of the stream
bw.Seek(0, SeekOrigin.Begin);
// update the size with the actual size we have now.
bw.Write((int)packetWriter.BaseStream.Length);
// send the buffer using the socket
return Send(ms.ToArray());
}
like this
leowest
leowestā€¢9mo ago
no
zoon_
zoon_OPā€¢9mo ago
wont this get the actiontype + message size
leowest
leowestā€¢9mo ago
that is to write the buffer that is not to read it
zoon_
zoon_OPā€¢9mo ago
oh i see the problem now
leowest
leowestā€¢9mo ago
how would it know u need to read exactly 16 if u dont send with it
zoon_
zoon_OPā€¢9mo ago
// update the size with the actual size we have now. bw.Write((int)packetWriter.BaseStream.Length); this might affect the actual actiontype data bc as u said it will overwrite
leowest
leowestā€¢9mo ago
or how would it know it needs to read 1100 or 200 this has nothing to do with actiontype that is just the first 4 bytes which are the size
zoon_
zoon_OPā€¢9mo ago
no i mean. if i write to the memorystream "actionType + messageData" and here. actiontype starts at position 0. if i go back and rewrite the size of the whole thing. you told me it would overwrite it not add new bytes. right ? // go back to the begin of the stream bw.Seek(0, SeekOrigin.Begin); this goes to position 0 like you said
leowest
leowestā€¢9mo ago
20 00 00 00 00 00 19 73 65 6E 64 69 6E 67 20 73 6F 6D 65 20 74 65 73 74 20 64 61 74 61 2E 2E 2E
^^ ^^ ^^ ^^ ** ** -----------------------------------------------------------------------------
^ size * action - message
20 00 00 00 00 00 19 73 65 6E 64 69 6E 67 20 73 6F 6D 65 20 74 65 73 74 20 64 61 74 61 2E 2E 2E
^^ ^^ ^^ ^^ ** ** -----------------------------------------------------------------------------
^ size * action - message
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
this is what u ended up with in the buffer
zoon_
zoon_OPā€¢9mo ago
and when i read it i can read the whole message in teh buffer by excluding the first 4 bytes of the size
leowest
leowestā€¢9mo ago
u dont exclude 4 bytes
zoon_
zoon_OPā€¢9mo ago
.
leowest
leowestā€¢9mo ago
you get the Length and remove 4 because the actiontype + message is Legth-4 so imagine u send that message
zoon_
zoon_OPā€¢9mo ago
thats what i meant yes
MODiX
MODiXā€¢9mo ago
leowest
var sizeBuffer = new byte[sizeof(int)];
var receivedBytes = client.Socket.Receive(sizeBuffer);
if (receivedBytes != sizeBuffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");
var sizeBuffer = new byte[sizeof(int)];
var receivedBytes = client.Socket.Receive(sizeBuffer);
if (receivedBytes != sizeBuffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");
Quoted by
<@1102729783969861782> from #Clients list (click here)
React with āŒ to remove this embed.
leowest
leowestā€¢9mo ago
what do u think that happens here? there is 20 bytes in the socket
zoon_
zoon_OPā€¢9mo ago
i create a sizeBuffer that holds 4 bytes. which where the size bytes would fit 20 00 00 00 4
leowest
leowestā€¢9mo ago
yes it takes 4 bytes from the socket so ur left with 16 bytes
zoon_
zoon_OPā€¢9mo ago
then i receive the whole message in the receiveBytes yes
MODiX
MODiXā€¢9mo ago
leowest
var size = BitConverter.ToInt32(sizeBuffer, 0);
var buffer = new byte[size];
receivedBytes = client.Socket.Receive(buffer);
if (receivedBytes != buffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");
var size = BitConverter.ToInt32(sizeBuffer, 0);
var buffer = new byte[size];
receivedBytes = client.Socket.Receive(buffer);
if (receivedBytes != buffer.Length)
throw new InvalidDataException($"Packet size wrong, received {receivedBytes} expected {sizeBuffer.Length}.");
Quoted by
<@1102729783969861782> from #Clients list (click here)
React with āŒ to remove this embed.
leowest
leowestā€¢9mo ago
but now here is the problem var size = BitConverter.ToInt32(sizeBuffer, 0); is still 20 what happens if u try to read 20 again?
zoon_
zoon_OPā€¢9mo ago
does it receive 4 bytes from the beginning or from the end ?
leowest
leowestā€¢9mo ago
always the head
zoon_
zoon_OPā€¢9mo ago
. so the message ? or the size the head is the part from the left right ?
leowest
leowestā€¢9mo ago
in the first step we read 4 bytes now there is 16 bytes left size is still 20 it tries to read 20 bytes from the socket what happens?
zoon_
zoon_OPā€¢9mo ago
exception probably
leowest
leowestā€¢9mo ago
exactly
zoon_
zoon_OPā€¢9mo ago
im trying to read more than what i received
leowest
leowestā€¢9mo ago
that is why u need to remoe 4 from the Length do u understand it now?
zoon_
zoon_OPā€¢9mo ago
yes so i need to send the size so the server knows the actual size of the message
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
so at first i receive 4 bytes which are the size bytes
leowest
leowestā€¢9mo ago
every message starts with the size so u always know how much u have to read until the next message so u read the size then u get the message
zoon_
zoon_OPā€¢9mo ago
bw.Write((int)packetWriter.BaseStream.Length); is this packetwriter integrated in memorystream ?
leowest
leowestā€¢9mo ago
the binarywriter writes to the memorystream and under the hood they both inherit from stream
zoon_
zoon_OPā€¢9mo ago
im triying to use the packetwriter its unkown
leowest
leowestā€¢9mo ago
ah my bad its just bw or ms let me check yeah its just bw
zoon_
zoon_OPā€¢9mo ago
its bw
leowest
leowestā€¢9mo ago
I forgot to rename it sorry
zoon_
zoon_OPā€¢9mo ago
yeah its okay
leowest
leowestā€¢9mo ago
was writing the example in a hurry heh slip
zoon_
zoon_OPā€¢9mo ago
all good bro thank you
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
so this just gets the message, writes it in bytes to the memoryStream
leowest
leowestā€¢9mo ago
now u have to add to it -sizeof(int) like we talked
zoon_
zoon_OPā€¢9mo ago
and then it goes back to adjust the 0 to the actual size but ofc minus 4 bytes so we dont include the size bytes
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
bc if the buffer reads 20 and the message is 16 it will give us an exception oh and in the part where i read. in the server do i start from position 4 ?
leowest
leowestā€¢9mo ago
yes no u do send 20 bytes
zoon_
zoon_OPā€¢9mo ago
yes i know
leowest
leowestā€¢9mo ago
but the message is only 16
zoon_
zoon_OPā€¢9mo ago
im talking ab when i read the message only
leowest
leowestā€¢9mo ago
we just talked about how its read u first read 4 bytes
zoon_
zoon_OPā€¢9mo ago
those are the sizes's bytes
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
then i use those and assign them to the buffer so it has the actual size of the message
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
after i do this do i send it directly without Encoding.utf8.getBytes ?
leowest
leowestā€¢9mo ago
it already encodes the string that is why u define it in the binary writer
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
so i can send it to the socket right away ? yeah
leowest
leowestā€¢9mo ago
that means when u do bw.Write(data.Message) it will already be utf8 encoded yes u can
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
like this ? so now the data sent to the server is the size + actiontype + message let me try and read it
zoon_
zoon_OPā€¢9mo ago
do i do the reading on two parts ?
No description
zoon_
zoon_OPā€¢9mo ago
like do i read twice ? first time i read the size only and second time i read the whole message ? how do i do that ? does the data not disappear ?
leowest
leowestā€¢9mo ago
yes u can't read the message if u dont know the size that is the whole point
zoon_
zoon_OPā€¢9mo ago
where does the data stay until i read it ? if its not in the buffer. then where is it
leowest
leowestā€¢9mo ago
it stays in the socket
zoon_
zoon_OPā€¢9mo ago
how it has no buffer to stay in
leowest
leowestā€¢9mo ago
Receive(buffer) means u want the socket to give u a buffer of that size period
zoon_
zoon_OPā€¢9mo ago
i see i thought it means. im receiving the bytes TO that buffer which is MY buffer
leowest
leowestā€¢9mo ago
you are receiving it to your buffer but if ur buffer is only of size 4 it wont give u 20 and to confirm that u have the bytesReceived
zoon_
zoon_OPā€¢9mo ago
sooo the other 16 bytes is kept in another buffer made by the socket ?
leowest
leowestā€¢9mo ago
sure u can think of it that way
zoon_
zoon_OPā€¢9mo ago
alright wait is it kept in the CLient socket or the Server socket ?
leowest
leowestā€¢9mo ago
every client u listen to u are essentially having a socket between the server and client there
zoon_
zoon_OPā€¢9mo ago
yes i know that
leowest
leowestā€¢9mo ago
so it will be ONE server socket that was open for that specific client
zoon_
zoon_OPā€¢9mo ago
using var br = new BinaryReader(incomingPacketStream); what does the incomingpacketstream do ?>
leowest
leowestā€¢9mo ago
did I forgot to rename that? its just the memorystream memorystream holds the buffer and feeds the reader with it
zoon_
zoon_OPā€¢9mo ago
ah i see so it uses the memorystream as a buffer to read bytes into it ?
leowest
leowestā€¢9mo ago
u give the buffer to the memorystream so the binary can acess the stream yes read bytes from it
zoon_
zoon_OPā€¢9mo ago
from it ? even though im making a new memorystream ? wont it have no data ?
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
oh nvm i didnt read properly
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
and ofc I forgot to rename incomingPacketStream to ms
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
here in the string messageReceived what does br.readstring do ? how does it know what to return is it because i moved the pointer that points to the bytes in the memorystream 2 bytes ? so now its pointing to the beginning of the message ?
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
and readstring returns the rest of the bytes as string right ? like translates it to string
leowest
leowestā€¢9mo ago
so binarywriter writes the length of the string along with it so it know how much to read
zoon_
zoon_OPā€¢9mo ago
hmm okay does it also write it at the beginning 4 bytes aswell ?
leowest
leowestā€¢9mo ago
zoon_
zoon_OPā€¢9mo ago
sick! did u just make that lmao
zoon_
zoon_OPā€¢9mo ago
why does it do that ?
No description
leowest
leowestā€¢9mo ago
yes and no I helped u awhile ago so I already had some of the code, so I just implemented what we dicussed in this thread
zoon_
zoon_OPā€¢9mo ago
šŸ˜­ that was fast nice
leowest
leowestā€¢9mo ago
looks like it connected and disconnected?
zoon_
zoon_OPā€¢9mo ago
yeah weird
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Communicator;
namespace Testing
{
internal class client
{
static bool flag = true;
static Socket clientSocket;
static void Main(string[] args)
{
Connect();
}
private static void Connect()
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.Write("Please enter the address of the server: ");
string ipAddress = Console.ReadLine();
clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipAddress), 8888));
while (flag)
{
Console.Write("Write the message you want to send.. ");
ClientMessage message = new ClientMessage(Console.ReadLine());
if (message.Message == "exit") flag = true;
else
{
message.Type = ActionType.MESSAGE;
Send(message);
}

}

}
private static void Send(ClientMessage message)
{
var size = 0;
using (var ms = new MemoryStream())
{
using (var bw = new BinaryWriter(ms, encoding: Encoding.UTF8))
{
//Write initial size
bw.Write(size);
//Write message type
bw.Write((short)message.Type);
//Write actual message
bw.Write(message.Message);
//Go back to the first byte to change the size to the actual size
bw.Seek(0, SeekOrigin.Begin);
//Writes the actual size
bw.Write((int)(bw.BaseStream.Length - 4));
clientSocket.Send(ms.ToArray());
}
}
}
}
}
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Communicator;
namespace Testing
{
internal class client
{
static bool flag = true;
static Socket clientSocket;
static void Main(string[] args)
{
Connect();
}
private static void Connect()
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.Write("Please enter the address of the server: ");
string ipAddress = Console.ReadLine();
clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipAddress), 8888));
while (flag)
{
Console.Write("Write the message you want to send.. ");
ClientMessage message = new ClientMessage(Console.ReadLine());
if (message.Message == "exit") flag = true;
else
{
message.Type = ActionType.MESSAGE;
Send(message);
}

}

}
private static void Send(ClientMessage message)
{
var size = 0;
using (var ms = new MemoryStream())
{
using (var bw = new BinaryWriter(ms, encoding: Encoding.UTF8))
{
//Write initial size
bw.Write(size);
//Write message type
bw.Write((short)message.Type);
//Write actual message
bw.Write(message.Message);
//Go back to the first byte to change the size to the actual size
bw.Seek(0, SeekOrigin.Begin);
//Writes the actual size
bw.Write((int)(bw.BaseStream.Length - 4));
clientSocket.Send(ms.ToArray());
}
}
}
}
}
can u see why ? bc i cant lmao
leowest
leowestā€¢9mo ago
if (message.Message == "exit") flag = true;
if (message.Message == "exit") flag = true;
shouldn't this be false? looks fine maybe the issue is on the server?
zoon_
zoon_OPā€¢9mo ago
lmfao yeah
zoon_
zoon_OPā€¢9mo ago
zoon_
zoon_OPā€¢9mo ago
here is the server
leowest
leowestā€¢9mo ago
static void Main(string[] args)
{
Initializer();
}
private static void Initializer()
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream ,ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
Thread listenerThread = new Thread(Listener);
listenerThread.Start();
}
static void Main(string[] args)
{
Initializer();
}
private static void Initializer()
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream ,ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
Thread listenerThread = new Thread(Listener);
listenerThread.Start();
}
it will exit the console and close the server
zoon_
zoon_OPā€¢9mo ago
oh bruhh ill make the main thread sleep nvm that would be dumb how can if ix this hmm
leowest
leowestā€¢9mo ago
can u $paste it to the site below
MODiX
MODiXā€¢9mo ago
If your code is too long, you can post to https://paste.mod.gg/ and copy the link into chat for others to see your shared code!
leowest
leowestā€¢9mo ago
discord embed files suck and I will brb
zoon_
zoon_OPā€¢9mo ago
alright tyt
zoon_
zoon_OPā€¢9mo ago
BlazeBin - kweeklvechug
A tool for sharing your source code with the world!
zoon_
zoon_OPā€¢9mo ago
i even tried to make it join so it waits for the new thread to terminate
No description
zoon_
zoon_OPā€¢9mo ago
soo the main thread paused
No description
zoon_
zoon_OPā€¢9mo ago
but it still disconnects
leowest
leowestā€¢9mo ago
I dont see why u need Initializer and a thread for the lsiten if you're moving it to the main method in the above example
static void Main()
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream ,ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
serverSocket.Listen(0);
while (true)
{
Socket clientSocket = serverSocket.Accept();
Console.WriteLine("Client has connected on " + DateTime.Now);
Thread clientThread = new Thread(ClientConnection);
clientThread.Start();
}
}
static void Main()
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream ,ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
serverSocket.Listen(0);
while (true)
{
Socket clientSocket = serverSocket.Accept();
Console.WriteLine("Client has connected on " + DateTime.Now);
Thread clientThread = new Thread(ClientConnection);
clientThread.Start();
}
}
zoon_
zoon_OPā€¢9mo ago
fair let me try why do u have the serverSocket.listen outside the while loop should it be outside the while
zoon_
zoon_OPā€¢9mo ago
still connects and disconnects
No description
leowest
leowestā€¢9mo ago
check the docs and see what it does
zoon_
zoon_OPā€¢9mo ago
ohh okay
leowest
leowestā€¢9mo ago
yes but the console no longer exits now right
zoon_
zoon_OPā€¢9mo ago
i mean its still open theres still a while true loop running
leowest
leowestā€¢9mo ago
so we solved 1 problem now we need to look and find out why its disconnecting give me a moment
zoon_
zoon_OPā€¢9mo ago
i think its here
private static void ClientConnection()
{
byte[] buffer;
int bytesRead = 0;
do
{
try
{
//Initialize the buffer so it can store the 4 bytes(size of message)
buffer = new byte[sizeof(int)];
bytesRead = serverSocket.Receive(buffer);
//If i received less bytes than 4 then the size would be incorrect..
if (bytesRead != buffer.Length)
{
throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");
}
//With the proper size we receive the whole message
int size = BitConverter.ToInt32(buffer, 0);
buffer = new byte[size];
bytesRead = serverSocket.Receive(buffer);
if (bytesRead != buffer.Length)
{
throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");
}
using (var ms = new MemoryStream(buffer))
{
using (var br = new BinaryReader(ms))
{
ActionType header = (ActionType)br.ReadInt16();
switch(header)
{
case ActionType.MESSAGE:
string messageReceived = br.ReadString();
Console.WriteLine($"A client has sent: {messageReceived}");
break;
}
}
}


}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
} while (bytesRead > 0);

}
private static void ClientConnection()
{
byte[] buffer;
int bytesRead = 0;
do
{
try
{
//Initialize the buffer so it can store the 4 bytes(size of message)
buffer = new byte[sizeof(int)];
bytesRead = serverSocket.Receive(buffer);
//If i received less bytes than 4 then the size would be incorrect..
if (bytesRead != buffer.Length)
{
throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");
}
//With the proper size we receive the whole message
int size = BitConverter.ToInt32(buffer, 0);
buffer = new byte[size];
bytesRead = serverSocket.Receive(buffer);
if (bytesRead != buffer.Length)
{
throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");
}
using (var ms = new MemoryStream(buffer))
{
using (var br = new BinaryReader(ms))
{
ActionType header = (ActionType)br.ReadInt16();
switch(header)
{
case ActionType.MESSAGE:
string messageReceived = br.ReadString();
Console.WriteLine($"A client has sent: {messageReceived}");
break;
}
}
}


}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
} while (bytesRead > 0);

}
in this method
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
int bytesRead = 0; this is the problem
zoon_
zoon_OPā€¢9mo ago
i had that in my winform app it was fine i think hold on let me check
leowest
leowestā€¢9mo ago
I will brb and explain
zoon_
zoon_OPā€¢9mo ago
okie yeah i have it lik that in my prev app weird
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
well for a start remove the try and catch so it doesn't hide the issue from u let the app crash it needs be strange that assumes the client socket is bad what I meant about this is, that u dont want that loop u want a loop you can cancel so u can actually exist the thread
zoon_
zoon_OPā€¢9mo ago
i see alrighty let me see
leowest
leowestā€¢9mo ago
but anyway that is not the issue do u have github reading code like this is making my head spin
zoon_
zoon_OPā€¢9mo ago
YEAH ill push the code on github hold on gimme some time
leowest
leowestā€¢9mo ago
yeah that would be easier so the whole picture
zoon_
zoon_OPā€¢9mo ago
alright give me some time
leowest
leowestā€¢9mo ago
I need to go out for a few minutes too I should be back in 40 minutes or so
zoon_
zoon_OPā€¢9mo ago
okay that should be fine! thank you bro oh my god the solution got deleted šŸ’€
leowest
leowestā€¢9mo ago
:catlaugh: how
zoon_
zoon_OPā€¢9mo ago
i changed to the master branch and it gave me an error now all of a sudden my solution is not there
leowest
leowestā€¢9mo ago
u can change back to master etc u can revert changes as long as u have no deleted it your self
zoon_
zoon_OPā€¢9mo ago
i cant open the solution to revert changes
leowest
leowestā€¢9mo ago
do from the command line git also works from the command line
zoon_
zoon_OPā€¢9mo ago
yk i didnt even push i just changed to master and it deleted it where do i even open the command line at ? which folder
leowest
leowestā€¢9mo ago
command prompt
zoon_
zoon_OPā€¢9mo ago
okay whats next
leowest
leowestā€¢9mo ago
then cd into the folder then
git checkout master
git checkout master
replace master to whatever it needs to be
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
the folder is empty
leowest
leowestā€¢9mo ago
then u must have deleted the entire folder oof
zoon_
zoon_OPā€¢9mo ago
bro i didnt yikes
leowest
leowestā€¢9mo ago
that is beyond git repair
zoon_
zoon_OPā€¢9mo ago
well
leowest
leowestā€¢9mo ago
are u sure ur not in the wrong folder?
zoon_
zoon_OPā€¢9mo ago
atleast i have my files here the client and server
leowest
leowestā€¢9mo ago
it should have a .git dir
zoon_
zoon_OPā€¢9mo ago
no. this is the solution folder ill just make a new project rn
leowest
leowestā€¢9mo ago
oof
zoon_
zoon_OPā€¢9mo ago
also. if i have ongoing work. should i push it to a new branch other than main and master ?
leowest
leowestā€¢9mo ago
well u have to have manually hit delete to delete the folder thou
zoon_
zoon_OPā€¢9mo ago
the funny thing is i didn't
leowest
leowestā€¢9mo ago
what were the last things u did then
zoon_
zoon_OPā€¢9mo ago
i opened my solution that is "testing.sln" and then i went to git changes the tab on vs and i changed to master and stashed the changes i think the project is stashed somewhere maybe where does vs stash stuff ?
leowest
leowestā€¢9mo ago
but u have no .git folder?
zoon_
zoon_OPā€¢9mo ago
yep weird
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
normally i twould be like that if .git does not exist it means it was manually deleted
zoon_
zoon_OPā€¢9mo ago
ill just make a new project yikes
leowest
leowestā€¢9mo ago
yeah that sucks more reason for u to have git working and commit more often this way its saved to github so if u lose it, u still have a copy on github
zoon_
zoon_OPā€¢9mo ago
okay we are back now let me put it on github
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
what are those files ? i see them often in my git change
leowest
leowestā€¢9mo ago
u forgot to add gitignire file when u create it dotnet new gitignore
zoon_
zoon_OPā€¢9mo ago
where do i write that ?
leowest
leowestā€¢9mo ago
u open the command prompt go to the folder with the command prompt and type it
zoon_
zoon_OPā€¢9mo ago
i added it the project
zoon_
zoon_OPā€¢9mo ago
GitHub
Projects/ChatApplicationTest at ongoing Ā· ZoonAttack/Projects
Projects i've been working on. Contribute to ZoonAttack/Projects development by creating an account on GitHub.
zoon_
zoon_OPā€¢9mo ago
wait it literally uploaded like 2 files wtf
leowest
leowestā€¢9mo ago
u should make a solution u add the gitignore in the solution not per project and u also create the git in the solution not per project
zoon_
zoon_OPā€¢9mo ago
what
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
i have a gitignore file
leowest
leowestā€¢9mo ago
huh no like
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
like this ? i used the dotnet new gitignore in the visual studio windows powershell
leowest
leowestā€¢9mo ago
yes but u did not create the git in that folder that is the problem
zoon_
zoon_OPā€¢9mo ago
i cloned a repo from github and copied the file into it and pushed it
leowest
leowestā€¢9mo ago
create a blank solution add git to it then add projects
zoon_
zoon_OPā€¢9mo ago
what projects you mean those projects in the screenshot ?
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
whats wrong with the way i did it ?
zoon_
zoon_OPā€¢9mo ago
cant find the create git repo
No description
leowest
leowestā€¢9mo ago
because the way u did u will have to create multiple github repositories instead of having 1 repository with your entire solution
zoon_
zoon_OPā€¢9mo ago
so youre sayin i should create one solution that has multiple projects ?
leowest
leowestā€¢9mo ago
normally that is how u do it
zoon_
zoon_OPā€¢9mo ago
lets say i have multiple projects that have nothing to do with eachother i should keep them under 1 solution ?
leowest
leowestā€¢9mo ago
yes what si wrong with that? that is how it usually works
zoon_
zoon_OPā€¢9mo ago
i see but for this example what im doing rn is creating multiple projects that communicate with eachother one for client one for server and one for communicator(which is a class library) it would be weird having them with other projects all under 1 solution
leowest
leowestā€¢9mo ago
no that is the exact purpose of the solution
zoon_
zoon_OPā€¢9mo ago
alright let me see .
leowest
leowestā€¢9mo ago
A solution is a workspace that combines multiple projects, which are usually related to each other. The construct is very useful in situations when some code needs to be shared among multiple projects.
zoon_
zoon_OPā€¢9mo ago
"which are usually related to each other." yeah
leowest
leowestā€¢9mo ago
which is your case šŸ˜‰
zoon_
zoon_OPā€¢9mo ago
yep .
leowest
leowestā€¢9mo ago
u right click the solution
zoon_
zoon_OPā€¢9mo ago
i did that theres already a git repo opened how do i close it do i delete the remote ?
leowest
leowestā€¢9mo ago
well I suppose because u created it on the project
zoon_
zoon_OPā€¢9mo ago
i created a different blank solution
leowest
leowestā€¢9mo ago
ok and it does nto show?
zoon_
zoon_OPā€¢9mo ago
nope there is an opened git repo
leowest
leowestā€¢9mo ago
u probably placed it inside a folder that already had git
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
yep hold on i deleted the .git folder and it still doesnt show to create a new repo
leowest
leowestā€¢9mo ago
u prob need to close visual studio and open again
zoon_
zoon_OPā€¢9mo ago
yep okay ill create a new repo
leowest
leowestā€¢9mo ago
when something simple becomes so complex šŸ˜‰
zoon_
zoon_OPā€¢9mo ago
i created it woohoo
leowest
leowestā€¢9mo ago
let's goo
zoon_
zoon_OPā€¢9mo ago
now i just add the projects right ?
leowest
leowestā€¢9mo ago
yep and the projects will by default already be covered by git
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
if i change this does it cause any problems later ? for the repo ?
leowest
leowestā€¢9mo ago
why would u want to change that?
zoon_
zoon_OPā€¢9mo ago
because i have 2 projects. client and server
leowest
leowestā€¢9mo ago
sure
zoon_
zoon_OPā€¢9mo ago
and i need both to start together
leowest
leowestā€¢9mo ago
open a new visual studio otherwise u will be lost debugging if both crash but u could change that if u want I just dont know if u can debug both u can set 1 to start and 1 to debug
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
how is there two repos wtf
leowest
leowestā€¢9mo ago
ah maybe u set it to the same github repository?
zoon_
zoon_OPā€¢9mo ago
i deleted the one called projects before i made a new one
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
normally it looks like this if nothing to commit
zoon_
zoon_OPā€¢9mo ago
yea lmao
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
what is even happening why is it so messy
leowest
leowestā€¢9mo ago
ah I see u have 2 branches
zoon_
zoon_OPā€¢9mo ago
yeah i have one that is main and one that is ongoing but i dont have two repos does each branch act as a repo
leowest
leowestā€¢9mo ago
well branches are the same repo its like a state and u swap between states as needed
zoon_
zoon_OPā€¢9mo ago
zoon_
zoon_OPā€¢9mo ago
well anyway heres the code
leowest
leowestā€¢9mo ago
but why did u create a branch k will check in a few
zoon_
zoon_OPā€¢9mo ago
because i thought its better to have another branch where i commit ongoing projects that havent been finished yet
leowest
leowestā€¢9mo ago
well u first develop once project is in a stable state good then when u create a branch to add a new feature
zoon_
zoon_OPā€¢9mo ago
yeah thats why i made another branch
leowest
leowestā€¢9mo ago
then u merge to main branch but its not in any stable state right now so dont worry too much so long as u commit often u should be good
zoon_
zoon_OPā€¢9mo ago
so should i commit to the main branch only ?
leowest
leowestā€¢9mo ago
yeah use the main branch only until u have something ur satisfied with
zoon_
zoon_OPā€¢9mo ago
and then what
leowest
leowestā€¢9mo ago
unless you had a crazy idea that involves rewriting the whole code u dont need a branch
zoon_
zoon_OPā€¢9mo ago
alright ill delete it later i have to go sleep now got uni tom
leowest
leowestā€¢9mo ago
alright
zoon_
zoon_OPā€¢9mo ago
check the code out please and tell me if u figured out anything new that's beencausing this error cheers
leowest
leowestā€¢9mo ago
as silly as it sounds ur not doing anything with the client socket, ur not passing it to the thread to use
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
Yikes Mb
leowest
leowestā€¢9mo ago
no worries been at it for too long plus the git issues
zoon_
zoon_OPā€¢9mo ago
ookayy so the sending messages works that's great now i can integrate it in my project
zoon_
zoon_OPā€¢9mo ago
zoon_
zoon_OPā€¢9mo ago
using System.Net.Sockets;
using System.Net;
using System.Text;
using Communicator;
namespace ChatApplicationTest
{
internal class client
{
static bool flag = true;
static Socket clientSocket;
static void Main(string[] args)
{
Connect();
}
private static void Connect()
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.Write("Please enter the address of the server: ");
string ipAddress = Console.ReadLine();
clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipAddress), 8888));
while (flag)
{
Console.Write("Write the message you want to send.. ");
ClientMessage message = new ClientMessage(Console.ReadLine());
if (message.Message == "exit") flag = true;
else
{
message.Type = ActionType.MESSAGE;
Send(message);
}

}

}
private static void Send(ClientMessage message)
{
var size = 0;
using (var ms = new MemoryStream())
{
using (var bw = new BinaryWriter(ms, encoding: Encoding.UTF8))
{
//Write initial size
bw.Write(size);
//Write message type
bw.Write((short)message.Type);
//Write actual message
bw.Write(message.Message);
//Go back to the first byte to change the size to the actual size
bw.Seek(0, SeekOrigin.Begin);
//Writes the actual size
bw.Write((int)(bw.BaseStream.Length - 4));
clientSocket.Send(ms.ToArray());
}
}
}
}
}
using System.Net.Sockets;
using System.Net;
using System.Text;
using Communicator;
namespace ChatApplicationTest
{
internal class client
{
static bool flag = true;
static Socket clientSocket;
static void Main(string[] args)
{
Connect();
}
private static void Connect()
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.Write("Please enter the address of the server: ");
string ipAddress = Console.ReadLine();
clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipAddress), 8888));
while (flag)
{
Console.Write("Write the message you want to send.. ");
ClientMessage message = new ClientMessage(Console.ReadLine());
if (message.Message == "exit") flag = true;
else
{
message.Type = ActionType.MESSAGE;
Send(message);
}

}

}
private static void Send(ClientMessage message)
{
var size = 0;
using (var ms = new MemoryStream())
{
using (var bw = new BinaryWriter(ms, encoding: Encoding.UTF8))
{
//Write initial size
bw.Write(size);
//Write message type
bw.Write((short)message.Type);
//Write actual message
bw.Write(message.Message);
//Go back to the first byte to change the size to the actual size
bw.Seek(0, SeekOrigin.Begin);
//Writes the actual size
bw.Write((int)(bw.BaseStream.Length - 4));
clientSocket.Send(ms.ToArray());
}
}
}
}
}
ill just save them here until i integrate it and update my github stuff i will also create a new repo that will include projects i work on
leowest
leowestā€¢9mo ago
normally u create a github repo per solutions its also good to have github because it shows people your progress etc what u know
zoon_
zoon_OPā€¢9mo ago
do you mean that i create a repo for every project ?
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
i see soo lets say i have several university projects that have nothing to do with eachother can i put them in folders and push them to a repo ?
leowest
leowestā€¢9mo ago
you could but imagine people looking at that repo it would be super confusing buy you can add a readme file and at least explain the purpose of that mega solution
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
does this look confusing :d
leowest
leowestā€¢9mo ago
with a readme to tell me waht each folder is yeah the name doesn't always translate intent
zoon_
zoon_OPā€¢9mo ago
yeah fair fair i think im redoing the whole project at this point lmao
leowest
leowestā€¢9mo ago
up to you there was a lot of information going on šŸ˜‰
zoon_
zoon_OPā€¢9mo ago
i suddenly hate github why is it so hard to push a project lol
leowest
leowestā€¢9mo ago
hard? its 1 button
zoon_
zoon_OPā€¢9mo ago
its messy
leowest
leowestā€¢9mo ago
how so?
zoon_
zoon_OPā€¢9mo ago
i keep pushing and it pushes only files not even my projects
leowest
leowestā€¢9mo ago
did u forgot the gitignore again
zoon_
zoon_OPā€¢9mo ago
no i added it to all projects šŸ’€ or should it be in the solution only
leowest
leowestā€¢9mo ago
u dont add it to all projects u just add it to the solution
zoon_
zoon_OPā€¢9mo ago
yk what ill create a new solution from the beginning
leowest
leowestā€¢9mo ago
lol
zoon_
zoon_OPā€¢9mo ago
ill make it from scratch with the new things ive learnt lets hope i dont have to do that again
leowest
leowestā€¢9mo ago
well gl maybe u should use git from the command line instead of vs then it will make it easier to understand what the git changes is doing
zoon_
zoon_OPā€¢9mo ago
it confuses me even more through the command line i just know git commit and git push . lmao
leowest
leowestā€¢9mo ago
$gitstarted
MODiX
MODiXā€¢9mo ago
git init initializes the repository dotnet new gitignore adds a .gitignore file git add . starts tracking all files git commit -m "[message]" creates a commit git remote add origin [url] adds a remote repository git push -u origin main first push, sets the remote as upstream git push all pushes after that can be just this Git cheat sheet
leowest
leowestā€¢9mo ago
Learn Git Branching
An interactive Git visualization tool to educate and challenge!
zoon_
zoon_OPā€¢9mo ago
cheers
leowest
leowestā€¢9mo ago
the last link is a good practice
zoon_
zoon_OPā€¢9mo ago
ill use it @leowestif i have a client class that holds his name and Socket should i have that under my server project or just in the solution ? because im not sure if im gonna be using it outside the server project anyway
leowest
leowestā€¢9mo ago
it would belong to the server project
zoon_
zoon_OPā€¢9mo ago
yeah i figured
leowest
leowestā€¢9mo ago
that is pretty internal stuff so if u want to send client data outside to other clients u would probably use a new class with only the needed information aka so called DTO
zoon_
zoon_OPā€¢9mo ago
well when i thought ab it if im gonna send any data that involves the client TO the client i would be sending names only so i think it's fine to have it under my server project im facing a weird problem when i double click on the button on my form im expecting it to generate the code in the .cs but it's not doing that
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
empty
leowest
leowestā€¢9mo ago
maybe restart vs? make sure your code builds
zoon_
zoon_OPā€¢9mo ago
it's not even generating code
leowest
leowestā€¢9mo ago
and the designer is not broken as well
zoon_
zoon_OPā€¢9mo ago
in the .cs of the designer
leowest
leowestā€¢9mo ago
yeah then restart vs
zoon_
zoon_OPā€¢9mo ago
okay!
leowest
leowestā€¢9mo ago
$vsdrunk
MODiX
MODiXā€¢9mo ago
* close VS * remove the hidden folder .vs * remove all bin and obj folder next to each csproj (DO NOT TOUCH THE .git FOLDER OR WHAT'S INSIDE) * restart vs
zoon_
zoon_OPā€¢9mo ago
oho kay so my client form has nothing now it's empty resetted šŸ’€ ugh
leowest
leowestā€¢9mo ago
what were the last few things u did like did u swap branches? did u stash something? did u write things directly to the designer?
zoon_
zoon_OPā€¢9mo ago
nope but ill just recreate stuff and then push it have you ever felt this frustrated ? lmao i have mid terms tomorrow. Operating systems and im over here working on this
leowest
leowestā€¢9mo ago
no because I often commit so I dont lose my stuff
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
I implement a feature, commit I fix a bug commit
zoon_
zoon_OPā€¢9mo ago
bet bet
leowest
leowestā€¢9mo ago
the thing with git is, it only works if u use it if u wait too long to use it and commit a bunch of stuff together then u lose track of potential bugs and whatnot if u add a feature and commit and something is now broken u can browse your last commit see what it changed and pin point the culprit
zoon_
zoon_OPā€¢9mo ago
ohh smart smart okay ill commit more
leowest
leowestā€¢9mo ago
https://github.com/PrismLibrary/Prism-Samples-Forms/commit/828e9f4bddd87ec8157a5cb529a448922f00e6da this is just an example of what it looks like when you're browsing on github u can also see it on visual studio
zoon_
zoon_OPā€¢9mo ago
seems complicated
leowest
leowestā€¢9mo ago
red is what was removed green was what was added in visual studio u can compare the file side by side so its much easier to follow
zoon_
zoon_OPā€¢9mo ago
also var size = 0; this is naturally int right ? so 4 bytes i see
leowest
leowestā€¢9mo ago
if u go to the git changes I think u double click a file that have the M on it it will show the changes previous to now
zoon_
zoon_OPā€¢9mo ago
what about the A
leowest
leowestā€¢9mo ago
A is addition so it wont show anything new but the file itself
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
so here I added that part that has a green square around it
zoon_
zoon_OPā€¢9mo ago
ohh makes sense i have a question
zoon_
zoon_OPā€¢9mo ago
let's say the client connected. i want to send to the server the username so it changes the client username and i want to send to the server that a client has connected
No description
zoon_
zoon_OPā€¢9mo ago
can i use the first message and use it again after sending it ? like this
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
or it wont matter if i create new instances of the clientMessage class ?
leowest
leowestā€¢9mo ago
the moment u accept the socket u know its connected
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
so connected can be ambiguous maybe u could send a JOIN action that sends the username upon connection? what I did on mine was when u connect u get a random Guest name that is sent to everyone and u can then change it
zoon_
zoon_OPā€¢9mo ago
i have it that u need to put a username
leowest
leowestā€¢9mo ago
the client message is suppose to be new instances
zoon_
zoon_OPā€¢9mo ago
i see alright
leowest
leowestā€¢9mo ago
but if u send modify and send it wont affect it because its not used anywhere else so u could technically do that too
zoon_
zoon_OPā€¢9mo ago
which is more efficient ? in terms of memory
leowest
leowestā€¢9mo ago
in this example sure but if u had a more complex example where u send the ClientMessage to a queue and that queue fires the message then it would be a problem
zoon_
zoon_OPā€¢9mo ago
yeah it wouldnt know which instance to fire
leowest
leowestā€¢9mo ago
because u would effectively change the content of it its not which to fire it would just be the same
zoon_
zoon_OPā€¢9mo ago
i see well ill keep it simply one instance for now if i face any problems ill change it
leowest
leowestā€¢9mo ago
i.e.: var message = new ClientMessage("abc", ActionType.Message); Send(message); message.Message = "username"; message.ActionType = ActionType.Username; Send(message); now both messages in the queue would be username and ActionType.Username if send was queuing the messages to be sent
zoon_
zoon_OPā€¢9mo ago
lmao yeah i get it
zoon_
zoon_OPā€¢9mo ago
would this be a proper way to give my clients initial name until i receive the USERNAME message from the client socket ?
No description
leowest
leowestā€¢9mo ago
they all would be named Guest
zoon_
zoon_OPā€¢9mo ago
yes that's fine may i see your random guest number generator ?>
leowest
leowestā€¢9mo ago
Name = $"Guest_{Random.Shared.NextInt()}";
zoon_
zoon_OPā€¢9mo ago
wat's random.shared ?
leowest
leowestā€¢9mo ago
Random is a class that generate random numbers Shared is an instance of it
zoon_
zoon_OPā€¢9mo ago
i see its like singleton ?
leowest
leowestā€¢9mo ago
so u dont have to initialize it, and can use it directly
zoon_
zoon_OPā€¢9mo ago
the instance
leowest
leowestā€¢9mo ago
sort of [
zoon_
zoon_OPā€¢9mo ago
i see theres only NextInt64 though lmao isnt that too big
leowest
leowestā€¢9mo ago
just Next then
zoon_
zoon_OPā€¢9mo ago
can i use the clientMessage class of my class library(communicator) to send messages from server to client ?
zoon_
zoon_OPā€¢9mo ago
BlazeBin - jcllryauuvfj
A tool for sharing your source code with the world!
zoon_
zoon_OPā€¢9mo ago
do you have any comment on this so far ? anything i could improve ?
leowest
leowestā€¢9mo ago
isn't that what ur doing?
zoon_
zoon_OPā€¢9mo ago
yes
leowest
leowestā€¢9mo ago
well do u want an honest comment of what to change or for now just a looks good it would work comment? also what is Utility.SocketConnected(clientSocket)
zoon_
zoon_OPā€¢9mo ago
honest opinion but at the same time tell me if im doing smth wrong
bool poll = s.Poll(0, SelectMode.SelectRead);
bool available = (s.Available == 0);
return (poll && available) ? false : true;
bool poll = s.Poll(0, SelectMode.SelectRead);
bool available = (s.Available == 0);
return (poll && available) ? false : true;
this to see if it's still connected
leowest
leowestā€¢9mo ago
u know clientSocket have a .Connected property right?
zoon_
zoon_OPā€¢9mo ago
yes but i heard that it checks at the current time not for a second even so i wanted to check if it's connected over like 1 second to make sure its connected
leowest
leowestā€¢9mo ago
I dont see how that will help u
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
what is that ?
leowest
leowestā€¢9mo ago
unless you're actively sending data between the 2 i.e.: a heartbeat
zoon_
zoon_OPā€¢9mo ago
this happens when i connect i see
leowest
leowestā€¢9mo ago
remove the try and catch so u can see the actual exception and where it throws dont use try and catch for while developing unless u know u must it hides the actual full error and location
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
it actively refused it i think i need to change the port am i correct ? i see alright
leowest
leowestā€¢9mo ago
is the server running? is the ip and port right?
zoon_
zoon_OPā€¢9mo ago
yes the server is running do you know the command prompt command that checks all active ports ?
leowest
leowestā€¢9mo ago
netstat -an
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
it's listening
leowest
leowestā€¢9mo ago
dont use
} while (bytesRead > 0);
} while (bytesRead > 0);
for your while loop! have a proper field u can access and change from true to false to terminate your app You also don't need it to be a dowhile, can be just a simple while(IsRunning) reduce the amount of nested ifs when possible it increases readability of your code:
using (var ms = new MemoryStream())
{
}
using (var ms = new MemoryStream())
{
}
Can be just
using var ms = new MemoryStream();
using var br = new BinaryReader(ms);
using var ms = new MemoryStream();
using var br = new BinaryReader(ms);
same for binaryreader/writer Instead of
if (Utility.SocketConnected(clientSocket))
{
}
else
{
clientSocket.Close();
}
if (Utility.SocketConnected(clientSocket))
{
}
else
{
clientSocket.Close();
}
Why not just use
if (!Utility.SocketConnected(clientSocket))
{
clientSocket.Close();
return;
}
if (!Utility.SocketConnected(clientSocket))
{
clientSocket.Close();
return;
}
It reduces yet another nested if from the code.
zoon_
zoon_OPā€¢9mo ago
i see i see good comments ngl thank you bro i think for the while hmm
leowest
leowestā€¢9mo ago
there is also more things I would suggest but I think they would be complex for u to execute now and might overload u like having a separated class that do the server operations
zoon_
zoon_OPā€¢9mo ago
it wouldnt hurt to know
leowest
leowestā€¢9mo ago
and instead of bloating your forms with all that code u would call for example
private void BTN_Connect_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(TB_Username.Text))
{
MessageBox.Show("Enter an username...");
return;
}

if (string.IsNullOrEmpty(TB_Address.Text))
{
MessageBox.Show("Enter an ip...");
return;
}

client.Connect(TB_Address.Text, 8888);
client.UpdateUsername(TB_Username.Text);
}
private void BTN_Connect_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(TB_Username.Text))
{
MessageBox.Show("Enter an username...");
return;
}

if (string.IsNullOrEmpty(TB_Address.Text))
{
MessageBox.Show("Enter an ip...");
return;
}

client.Connect(TB_Address.Text, 8888);
client.UpdateUsername(TB_Username.Text);
}
the readdata and send would also be part of the client class but tbh I wouldn't bother with that now get it working then refactor and make it better as long as you can complete it its one step forward from there u can improve it, refactor etc
zoon_
zoon_OPā€¢9mo ago
okie thank you for noting that for my do while what variable should i put in it ? to check
leowest
leowestā€¢9mo ago
I usually just create an state across the app I can check for i.e.: bool isRunning; that I enable when I connect and disable when I am leaving the app and call the appropriate methods before calling it then I connect, it succeed? then I change it to true
zoon_
zoon_OPā€¢9mo ago
what appropriate method ? would u call before
leowest
leowestā€¢9mo ago
well that depends on what ur app works right if my app is closing and I have user data I need to save then I would call a method that saves that data if I have a connection to something open then maybe send a message saying im disconnecting before closing the connection it really depends on what ur app does and what u think is needed to be done before it closes
zoon_
zoon_OPā€¢9mo ago
private void ClientConnection(Client client)
{
byte[] buffer;
int bytesRead = 1;
while (isReading)
{
using var ms = new MemoryStream();
using var br = new BinaryReader(ms);
if (!Utility.SocketConnected(client.Socket))
{
TB_Log.AppendText($"Client({client.Name}) has disconnected from the server");
clients.Remove(client);
isReading = false;
}
buffer = new byte[sizeof(int)];
bytesRead = client.Socket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");

int size = BitConverter.ToInt32(buffer, 0);
buffer = new byte[size];
bytesRead = client.Socket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");

ActionType type = (ActionType)br.ReadInt16();
switch (type)
{
case ActionType.MESSAGE:
string messageReceived = br.ReadString();
TB_Log.AppendText($"({client.Name}) sent: {messageReceived}{Environment.NewLine}");
break;
case ActionType.USERNAME:
messageReceived = br.ReadString();
client.Name = messageReceived;
TB_Log.AppendText($"Set Client: {client.Name}'s name to {messageReceived}");
break;
}
}
}
private void ClientConnection(Client client)
{
byte[] buffer;
int bytesRead = 1;
while (isReading)
{
using var ms = new MemoryStream();
using var br = new BinaryReader(ms);
if (!Utility.SocketConnected(client.Socket))
{
TB_Log.AppendText($"Client({client.Name}) has disconnected from the server");
clients.Remove(client);
isReading = false;
}
buffer = new byte[sizeof(int)];
bytesRead = client.Socket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");

int size = BitConverter.ToInt32(buffer, 0);
buffer = new byte[size];
bytesRead = client.Socket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");

ActionType type = (ActionType)br.ReadInt16();
switch (type)
{
case ActionType.MESSAGE:
string messageReceived = br.ReadString();
TB_Log.AppendText($"({client.Name}) sent: {messageReceived}{Environment.NewLine}");
break;
case ActionType.USERNAME:
messageReceived = br.ReadString();
client.Name = messageReceived;
TB_Log.AppendText($"Set Client: {client.Name}'s name to {messageReceived}");
break;
}
}
}
i edited it this is the server
private void ReadingData()
{
byte[] buffer;
int bytesRead = 0;
//try
//{
using var ms = new MemoryStream();
using var br = new BinaryReader(ms);
while (isReading)
{
if (!Utility.SocketConnected(clientSocket))
{
clientSocket.Close();
isReading = false;
return;
}
buffer = new byte[sizeof(int)];
bytesRead = clientSocket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");

int size = BitConverter.ToInt32(buffer, 0);
buffer = new byte[size];
bytesRead = clientSocket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");

ActionType type = (ActionType)br.ReadInt16();
switch (type)
{
case ActionType.MESSAGE:
string messageReceived = br.ReadString();
TB_ChatBox.AppendText($"{messageReceived}{Environment.NewLine}");
break;
}
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message);
//}
}
}
private void ReadingData()
{
byte[] buffer;
int bytesRead = 0;
//try
//{
using var ms = new MemoryStream();
using var br = new BinaryReader(ms);
while (isReading)
{
if (!Utility.SocketConnected(clientSocket))
{
clientSocket.Close();
isReading = false;
return;
}
buffer = new byte[sizeof(int)];
bytesRead = clientSocket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");

int size = BitConverter.ToInt32(buffer, 0);
buffer = new byte[size];
bytesRead = clientSocket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");

ActionType type = (ActionType)br.ReadInt16();
switch (type)
{
case ActionType.MESSAGE:
string messageReceived = br.ReadString();
TB_ChatBox.AppendText($"{messageReceived}{Environment.NewLine}");
break;
}
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message);
//}
}
}
and this is the client
leowest
leowestā€¢9mo ago
if u do not return on that if it will run all the code under it
zoon_
zoon_OPā€¢9mo ago
i see yeah mb also. when i allow my server through the firewall which .exe should i put ? the one in debug ?
leowest
leowestā€¢9mo ago
and yes for nwo remove all try and catch and let the exception explode so u know what it is and deal with waht u can deal
zoon_
zoon_OPā€¢9mo ago
yes
leowest
leowestā€¢9mo ago
normally u would use Release mode so u right click your project and create a Publish and it will build it in release mode and create a release output folder with all the files
zoon_
zoon_OPā€¢9mo ago
i see new error
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
your message is not what ur expecting hover your mouse on bytesRead
zoon_
zoon_OPā€¢9mo ago
it's 8
leowest
leowestā€¢9mo ago
also how do u read it if ur memorystream is empty ...
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
how is it empty oh shit wait šŸ˜­
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
okay i know the fix to this error i need to invoke that method on the ui thread
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
umm what is the textbox passed as like what is it's type ? if i want to pass it as a parameter
leowest
leowestā€¢9mo ago
im not following maybe u want to show me what you're doing instead
zoon_
zoon_OPā€¢9mo ago
private void UpdateUI(string text)
{
if(TB_Log.InvokeRequired)
{
TB_Log.Invoke(new Action(() => UpdateUI(text)));
}
else
{
TB_Log.AppendText($"{text}{Environment.NewLine}");
}
}
private void UpdateUI(string text)
{
if(TB_Log.InvokeRequired)
{
TB_Log.Invoke(new Action(() => UpdateUI(text)));
}
else
{
TB_Log.AppendText($"{text}{Environment.NewLine}");
}
}
i want to make one method of this in my utility class that takes Textbox and text and i update the ui based on the textbox and text instead of creating it multiple times for my client and server
leowest
leowestā€¢9mo ago
I dont think that should be a utility method since its tied to winform
zoon_
zoon_OPā€¢9mo ago
i see yeah
leowest
leowestā€¢9mo ago
u would have to reference winform into the library, just to use the type of the textbox not a good approach imo
zoon_
zoon_OPā€¢9mo ago
ill just use it like this
private void UpdateUI(TextBox tb,string text)
{
if (tb.InvokeRequired)
{
tb.Invoke(new Action(() => UpdateUI(tb, text)));
}
else
{
tb.AppendText($"{text}{Environment.NewLine}");
}
}
private void UpdateUI(TextBox tb,string text)
{
if (tb.InvokeRequired)
{
tb.Invoke(new Action(() => UpdateUI(tb, text)));
}
else
{
tb.AppendText($"{text}{Environment.NewLine}");
}
}
in my client form code and server form code
leowest
leowestā€¢9mo ago
sure
zoon_
zoon_OPā€¢9mo ago
yay ayee
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
how do i check if my server socket is still running ?
leowest
leowestā€¢9mo ago
u make a heartbeat and update a property to tell if the heartbeat fails then the client lost connection its basically a ping pong message server sends ping client anwers with pong
zoon_
zoon_OPā€¢9mo ago
what do you mean by heasrtbeat
zoon_
zoon_OPā€¢9mo ago
why does it say this
No description
zoon_
zoon_OPā€¢9mo ago
when i have above that if the client isnt connected it returns lol i just closed the client form which inherently closed the connection okay i fixed it by toggling the isReading when form closed to false
zoon_
zoon_OPā€¢9mo ago
now this
No description
leowest
leowestā€¢9mo ago
well u only start that thread after u connect to the server never before so that should be a problem
zoon_
zoon_OPā€¢9mo ago
yes how
leowest
leowestā€¢9mo ago
did u try to reconnect? and that is what that error came from?
zoon_
zoon_OPā€¢9mo ago
nono i just connected and i closed the client form
if (!Utility.SocketConnected(client.Socket))
{
UpdateUI(TB_Log, $"Client({client.Name}) has disconnected from the server");
clients.Remove(client);
isReading = false;
return;
}
if (!Utility.SocketConnected(client.Socket))
{
UpdateUI(TB_Log, $"Client({client.Name}) has disconnected from the server");
clients.Remove(client);
isReading = false;
return;
}
leowest
leowestā€¢9mo ago
ah that's on the server ok so what happens there is
zoon_
zoon_OPā€¢9mo ago
this right here should annoounce in the log that someone has disconnected
leowest
leowestā€¢9mo ago
the server does not know u closed the client if u do not send a message to the server before doing so so when the server tries to read the socket it throws the exception
zoon_
zoon_OPā€¢9mo ago
i see i see
leowest
leowestā€¢9mo ago
so the proper way of doing this is u would send a message and then disconnect so the server can properly close the socket and remove that client but at the same time you might have to catch that specif exception on the server because its not always that a client will gracefully close itself but u dont just wrap a try catcn with Exception u add the specific exception to it
zoon_
zoon_OPā€¢9mo ago
yeah im on that
private void ClientConnection(Client client)
{
byte[] buffer;
int bytesRead = 1;
while (isReading)
{
if (!Utility.SocketConnected(client.Socket))
{
isReading = false;
return;
}
//try
//{
buffer = new byte[sizeof(int)];
bytesRead = client.Socket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");

int size = BitConverter.ToInt32(buffer, 0);
buffer = new byte[size];
bytesRead = client.Socket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");
using var ms = new MemoryStream(buffer);
using var br = new BinaryReader(ms);
ActionType type = (ActionType)br.ReadInt16();
switch (type)
{
case ActionType.MESSAGE:
string messageReceived = br.ReadString();
UpdateUI(TB_Log, $"({client.Name}) sent: {messageReceived}{Environment.NewLine}");
break;
case ActionType.USERNAME:
messageReceived = br.ReadString();
client.Name = messageReceived;
UpdateUI(TB_Log, $"Set Client: {client.Name}'s name to {messageReceived}");
break;
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
clients.Remove(client);
UpdateUI(TB_Log, $"{client.Name} {messageReceived}");
break;
}
}
}
private void ClientConnection(Client client)
{
byte[] buffer;
int bytesRead = 1;
while (isReading)
{
if (!Utility.SocketConnected(client.Socket))
{
isReading = false;
return;
}
//try
//{
buffer = new byte[sizeof(int)];
bytesRead = client.Socket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");

int size = BitConverter.ToInt32(buffer, 0);
buffer = new byte[size];
bytesRead = client.Socket.Receive(buffer);
if (bytesRead != buffer.Length) throw new InvalidDataException($"Got {bytesRead} Expected {buffer.Length}");
using var ms = new MemoryStream(buffer);
using var br = new BinaryReader(ms);
ActionType type = (ActionType)br.ReadInt16();
switch (type)
{
case ActionType.MESSAGE:
string messageReceived = br.ReadString();
UpdateUI(TB_Log, $"({client.Name}) sent: {messageReceived}{Environment.NewLine}");
break;
case ActionType.USERNAME:
messageReceived = br.ReadString();
client.Name = messageReceived;
UpdateUI(TB_Log, $"Set Client: {client.Name}'s name to {messageReceived}");
break;
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
clients.Remove(client);
UpdateUI(TB_Log, $"{client.Name} {messageReceived}");
break;
}
}
}
so this is more appropriate ?
if (!Utility.SocketConnected(client.Socket))
{
isReading = false;
return;
}
if (!Utility.SocketConnected(client.Socket))
{
isReading = false;
return;
}
should i remove this line and just put all what's in it in the disconnected part ?
leowest
leowestā€¢9mo ago
you would have something like this
try
{
bytesRead = client.Socket.Receive(buffer);
}
catch (SocketException soex)
{
// dispose of socket
// remove client from the list
// Log the expcetion
// Broadcast to other that user left
return;
}
try
{
bytesRead = client.Socket.Receive(buffer);
}
catch (SocketException soex)
{
// dispose of socket
// remove client from the list
// Log the expcetion
// Broadcast to other that user left
return;
}
and you would also wrap the Send part too
zoon_
zoon_OPā€¢9mo ago
i see
zoon_
zoon_OPā€¢9mo ago
zoon_
zoon_OPā€¢9mo ago
how about this ?
leowest
leowestā€¢9mo ago
$paste
MODiX
MODiXā€¢9mo ago
If your code is too long, you can post to https://paste.mod.gg/ and copy the link into chat for others to see your shared code!
zoon_
zoon_OPā€¢9mo ago
stuff are really messy now im trying to handle disconnections when the form closes but its messy ill send u the code
zoon_
zoon_OPā€¢9mo ago
BlazeBin - bdmrrlymdjrg
A tool for sharing your source code with the world!
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
this happens when i close the client form
zoon_
zoon_OPā€¢9mo ago
this happens when i close the server form
No description
leowest
leowestā€¢9mo ago
that is another exception to the rule because u can't terminate it in blocking mode only in async mode so u can wrap that one in a try and catch as well only that line needs to be because u dont want to hide other exceptions from happening
zoon_
zoon_OPā€¢9mo ago
only that one line ? okay you mean i cant terminate it unles im in async mode ?
leowest
leowestā€¢9mo ago
this one I already explained above u do this
zoon_
zoon_OPā€¢9mo ago
but i did do that
leowest
leowestā€¢9mo ago
ah that is on the client side when server closes?
zoon_
zoon_OPā€¢9mo ago
this is on th client side when i close the client form
leowest
leowestā€¢9mo ago
this one I mean so yeah u would add an event to your form I think FormClosing its called
zoon_
zoon_OPā€¢9mo ago
i did
private void ClientHome_FormClosing(object sender, FormClosingEventArgs e)
{
message = new ClientMessage("Disconnected..", ActionType.DISCONNECTED);
Send(message);
isReading = false;
clientSocket.Close();
}
private void ClientHome_FormClosing(object sender, FormClosingEventArgs e)
{
message = new ClientMessage("Disconnected..", ActionType.DISCONNECTED);
Send(message);
isReading = false;
clientSocket.Close();
}
so it's literally sending to the server. "hey im disconnecting" then closes the socket im afraid its closing before i send the message and receive it and complete it
leowest
leowestā€¢9mo ago
yeah I will say in a bit the page is having a hard time to load your code
zoon_
zoon_OPā€¢9mo ago
okie soo i was right the socket is closing before the server receives the message and processes it i commented the last line where it cloes the socket and it didnt throw exception or anything it just logged
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
i think i need to use await
leowest
leowestā€¢9mo ago
no Send is blocking it will not go to the next code if it has not executed
zoon_
zoon_OPā€¢9mo ago
then why did it work when i commented the line lmao weird
leowest
leowestā€¢9mo ago
commented what line?
zoon_
zoon_OPā€¢9mo ago
clientSocket.Close(); this
leowest
leowestā€¢9mo ago
ah u mean the message was not reaching the server?
zoon_
zoon_OPā€¢9mo ago
yeah maybe the socket for some reason closes before the message is received and processed and executed
leowest
leowestā€¢9mo ago
ah there we go
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
When using a connection-oriented Socket, always call the Shutdown method before closing the Socket. This ensures that all data is sent and received on the connected socket before it is closed. Call the Close method to free all managed and unmanaged resources associated with the Socket. Do not attempt to reuse the Socket after closing.
zoon_
zoon_OPā€¢9mo ago
ohh okay let me try so i call the shutdown before the close ?
leowest
leowestā€¢9mo ago
exactly as the example above
zoon_
zoon_OPā€¢9mo ago
i didnt know c# has finally{} lol
leowest
leowestā€¢9mo ago
well it is try {} catch {} finally {}
zoon_
zoon_OPā€¢9mo ago
yes its in python too so the .shutdown ensures that all messages being sent are received first ?
MODiX
MODiXā€¢9mo ago
leowest
When using a connection-oriented Socket, always call the Shutdown method before closing the Socket. This ensures that all data is sent and received on the connected socket before it is closed. Call the Close method to free all managed and unmanaged resources associated with the Socket. Do not attempt to reuse the Socket after closing.
Quoted by
<@1102729783969861782> from #Clients list (click here)
React with āŒ to remove this embed.
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
okay soooo šŸ’€
leowest
leowestā€¢9mo ago
are u sending something to the client after its closed
zoon_
zoon_OPā€¢9mo ago
no to the client ? wait no im not
leowest
leowestā€¢9mo ago
ah my bad that ist he server
zoon_
zoon_OPā€¢9mo ago
private void ClientHome_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
message = new ClientMessage("Disconnected..", ActionType.DISCONNECTED);
Send(message);
isReading = false;
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
}
private void ClientHome_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
message = new ClientMessage("Disconnected..", ActionType.DISCONNECTED);
Send(message);
isReading = false;
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
}
this is my form closing im not sending anything
leowest
leowestā€¢9mo ago
yes that sends a message to the server its fine so does the server get that message? and then that exception happens? if (bytesRead == 0) break; like does the server get the Disconnect action? also why did u wrap teh whole things.... lol
zoon_
zoon_OPā€¢9mo ago
Oh mb Also Won't the finally block execute anyways ? Even if there was an exception caught ?
leowest
leowestā€¢9mo ago
it will but why wrap unnecessary code in it
zoon_
zoon_OPā€¢9mo ago
Is that bad
leowest
leowestā€¢9mo ago
it can be imagine what u were doing before
zoon_
zoon_OPā€¢9mo ago
Soo it won't trll me what's wrong with my code if I put it in the try
leowest
leowestā€¢9mo ago
for example in here look at how many points of failure the exception could have and u hide all of it could be the first receive the 2nd the bitconverter
zoon_
zoon_OPā€¢9mo ago
Yeah fair enough lmao
leowest
leowestā€¢9mo ago
the chatbox the throws so only ever wrap what is essentially necessary anyway does ur server get the disconnect message then it goes back to the Receive and throws? if so its because u need to end the loop and handle things on the disconnect
zoon_
zoon_OPā€¢9mo ago
I'll have to put a breakpoint yo see To I'm supposed to handle things on the server side right m ?*
leowest
leowestā€¢9mo ago
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
clients.Remove(client);
UpdateUI(TB_Log, $"{client.Name} {messageReceived}");
break;
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
clients.Remove(client);
UpdateUI(TB_Log, $"{client.Name} {messageReceived}");
break;
ah yes ur not returning
zoon_
zoon_OPā€¢9mo ago
Oh right
leowest
leowestā€¢9mo ago
change break to return;
zoon_
zoon_OPā€¢9mo ago
Ok
leowest
leowestā€¢9mo ago
and close the socket ur not closing it
zoon_
zoon_OPā€¢9mo ago
Which socket ? But I'm closing it from the client home page form
leowest
leowestā€¢9mo ago
client.Socket
zoon_
zoon_OPā€¢9mo ago
. Client socket .close
leowest
leowestā€¢9mo ago
client code is client code server code is server code
zoon_
zoon_OPā€¢9mo ago
So they r not the same socket ?
leowest
leowestā€¢9mo ago
Closes the Socket connection and releases all associated resources.
when u open a socket it does a lot of things under the hood that needs to be disposed of
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
always refer to the docs for the specific things they explain a lot https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.close?view=net-8.0
zoon_
zoon_OPā€¢9mo ago
i have problems with reading docs šŸ˜‚ but ill try
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
client.Socket.Close();
clients.Remove(client);
UpdateUI(TB_Log, $"{client.Name} {messageReceived}");
return;
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
client.Socket.Close();
clients.Remove(client);
UpdateUI(TB_Log, $"{client.Name} {messageReceived}");
return;
so like this ?
leowest
leowestā€¢9mo ago
yep
zoon_
zoon_OPā€¢9mo ago
still threw the same exception
leowest
leowestā€¢9mo ago
I mean it shouldn't since it leaves the loop breakpoint and see what is going on but if it does not leave the loop then isReading = false;
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
this exception happens it first accesses the ACTIONTYPE.DISCONNECTEd then executes the first line then it showes me this then it logs "disconnected" but for some reason when i remove the breakpoint
leowest
leowestā€¢9mo ago
that is wrong
zoon_
zoon_OPā€¢9mo ago
it doesnt do that and instead throws exception
leowest
leowestā€¢9mo ago
your loop does not loop while its running its a workflow it will run the loop to the end before it goes back to the top if return is not exiting the loop
zoon_
zoon_OPā€¢9mo ago
where do u want me to put the brekapoint at
leowest
leowestā€¢9mo ago
then something is wrong in your code
zoon_
zoon_OPā€¢9mo ago
oh wait nvm i put the breakpoint in the server
leowest
leowestā€¢9mo ago
u can put the breakpoing inside the disconnect
zoon_
zoon_OPā€¢9mo ago
not the client
leowest
leowestā€¢9mo ago
it is in the server that error is in the server no?
zoon_
zoon_OPā€¢9mo ago
i did put it there no in the client i saw it wrong
leowest
leowestā€¢9mo ago
ah me too I guess
zoon_
zoon_OPā€¢9mo ago
okay so what happens is it goes to the Send(message) method completes it then throws the exceptin right away
leowest
leowestā€¢9mo ago
ok so it throws because shutdown canceled the receive method so u might need to do If (bytesRead == 0) return;
zoon_
zoon_OPā€¢9mo ago
i see alright
leowest
leowestā€¢9mo ago
right after the first receive method
zoon_
zoon_OPā€¢9mo ago
yes okay it worked
leowest
leowestā€¢9mo ago
because what happens on the client is this
while (isRunning)
{
bytesReceive = socket.Receive() // code waits here until the socket receives something or shutdown terminates this
}
while (isRunning)
{
bytesReceive = socket.Receive() // code waits here until the socket receives something or shutdown terminates this
}
in this case shutdown terminated it because u told it to close both receive and send method if nothing else is on the pipe to be received/sent
zoon_
zoon_OPā€¢9mo ago
yeah true true understood shutdown stops receiving so it received 0
leowest
leowestā€¢9mo ago
a lot of small details it returns 0 not receives šŸ˜›
zoon_
zoon_OPā€¢9mo ago
i see šŸ˜‚ okie
zoon_
zoon_OPā€¢9mo ago
this happens when i close the server form
No description
leowest
leowestā€¢9mo ago
well the server is more complex
zoon_
zoon_OPā€¢9mo ago
i see šŸ˜‚
leowest
leowestā€¢9mo ago
u have to iterate over all the open clients
zoon_
zoon_OPā€¢9mo ago
and close all sockets ?
leowest
leowestā€¢9mo ago
foreach (var client in thenameofyourListofClient) { Send(....); try { client.Socket.Shutdown(...both); } finally { client.Socket.Close(); } serverSocket.Dispose(); } u dont need to call Environment.Exit(0) also that is the wrong event u want the one called FormClosing not Closed
zoon_
zoon_OPā€¢9mo ago
i see i see yeah
leowest
leowestā€¢9mo ago
so basically u broadcast to all connected clients the server is shutdown then clients wont send a message to server they will just disconnect then u shutdown / close all clients sockets then u dispose the server and done
zoon_
zoon_OPā€¢9mo ago
so i loop over my clients list disconnect all of them ? and i dispose the server ?
leowest
leowestā€¢9mo ago
loop over, send a disconnecting for the clients to disconnect shutdown / close etc same process u did on the client when u close but reversed
zoon_
zoon_OPā€¢9mo ago
i see so i have to send a message that the server is disconnecting ? i cant just force them to disconnect from the server ? it seems easier that way
leowest
leowestā€¢9mo ago
u send the ActionType.Disconnect then u will have N clients throwing an error u will have to catch not ideal this is called gracefully shutdown when u properly notify all your clients to disconnect
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
before turning off
zoon_
zoon_OPā€¢9mo ago
okay i will do that what should the clients do when i tell them the server is disconnecting ?
leowest
leowestā€¢9mo ago
the path of properly coding is arduous šŸ˜›
zoon_
zoon_OPā€¢9mo ago
yeah.. but its fun
leowest
leowestā€¢9mo ago
well u would stop the loops, close the socket and maybe post a message to the textbox saying server disconnected
zoon_
zoon_OPā€¢9mo ago
okay fair
leowest
leowestā€¢9mo ago
and u might also need to do the same thing u did on the receive for the bytesReceived 0
zoon_
zoon_OPā€¢9mo ago
i will do that
leowest
leowestā€¢9mo ago
its the pretty much the same proccess of when a client disconnects but reversed
zoon_
zoon_OPā€¢9mo ago
i will do that tomorrow i have to sleep now got exam tom
leowest
leowestā€¢9mo ago
and u would have to update this with
if (clientSocket == null || !client.Socket.Connected)
{
return;
}
if (clientSocket == null || !client.Socket.Connected)
{
return;
}
so it skips that if the socket is null or already disconnected on the client there is no point disconnecting and sending a message to the server if you're already disconnected šŸ˜›
zoon_
zoon_OPā€¢9mo ago
well i have to do that in order to broadcast to other clients that someone has disconnected so i send to the server that client{name} has disconnected ohh
leowest
leowestā€¢9mo ago
the above is client not server
zoon_
zoon_OPā€¢9mo ago
nvm i understand what u mean yes it checks if the client already disconnected yeah ive put the send message in my utility class so i can use it in both server and client and right before i do serverSocket.shutdown i sent a actiontype.disconnect message from the server socket to connected sockets and on that disconnect the clients will stop the loop, close their sockets and post a message to the chatbox
case ActionType.DISCONNECTED:
isReading = false;
UpdateUI(TB_ChatBox, "The server has been shut down..");
try
{
clientSocket.Close();
}
catch (SocketException soex)
{
MessageBox.Show(soex.Message);
}
break;
case ActionType.DISCONNECTED:
isReading = false;
UpdateUI(TB_ChatBox, "The server has been shut down..");
try
{
clientSocket.Close();
}
catch (SocketException soex)
{
MessageBox.Show(soex.Message);
}
break;
` this is in the client
private void ServerHome_FormClosed(object sender, FormClosedEventArgs e)
{
isReading = false;
try
{
if (serverSocket != null)
{
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
Utility.Send(serverSocket, message);

serverSocket.Shutdown(SocketShutdown.Both);
}
}
finally
{
serverSocket.Close();
}
Environment.Exit(0);
}
private void ServerHome_FormClosed(object sender, FormClosedEventArgs e)
{
isReading = false;
try
{
if (serverSocket != null)
{
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
Utility.Send(serverSocket, message);

serverSocket.Shutdown(SocketShutdown.Both);
}
}
finally
{
serverSocket.Close();
}
Environment.Exit(0);
}
zoon_
zoon_OPā€¢9mo ago
i face this exception in my send method
No description
zoon_
zoon_OPā€¢9mo ago
shouldnt this work ? i also changed from serverhome.formclosed to formclosing i am a bit confused on using Socket.send when i use serverSocket.send. am i sending bytes to the server ? or the clients
leowest
leowestā€¢9mo ago
why?
zoon_
zoon_OPā€¢9mo ago
why what
leowest
leowestā€¢9mo ago
I told u is the same process shutdown, close also check before if its not null and connected
zoon_
zoon_OPā€¢9mo ago
okay
leowest
leowestā€¢9mo ago
wrong event ServerHome_FormClosed? why Environment.Exit(0);? also return not break
zoon_
zoon_OPā€¢9mo ago
i changed that i just forgot to send it
leowest
leowestā€¢9mo ago
ok and why Environment.Exit(0);?
zoon_
zoon_OPā€¢9mo ago
i wanted the app to close if the server is turned off but i deleted it
leowest
leowestā€¢9mo ago
that is not closing the app that is killing it half way
zoon_
zoon_OPā€¢9mo ago
huh ? šŸ’€ i see i didnt know
leowest
leowestā€¢9mo ago
when u close your app it does a bunch of stop until it closes completely calling that will literally make it stop anythign its doing and terminate its not a console app and even in a console app u dont necessarrily need to call it for example static void Main() { some code Environment.Exit } that is meaningless because after some code it already reachs the end of the app so it will exit anyway so in winforms if u wanted to exit your app with an error u could call that, but if you want it to gracefully exit just let it close by itself, terminate any running threads etc
zoon_
zoon_OPā€¢9mo ago
oaky .
leowest
leowestā€¢9mo ago
depends where its called no? u moved it to the utility library
zoon_
zoon_OPā€¢9mo ago
this exception is fixed now. im facing this
No description
leowest
leowestā€¢9mo ago
I suppose that is the same issue as before
zoon_
zoon_OPā€¢9mo ago
this is in the client
leowest
leowestā€¢9mo ago
u disconnect
zoon_
zoon_OPā€¢9mo ago
yeah
leowest
leowestā€¢9mo ago
does not return the loop and forget to do the if (bytesReceived == 0) { // app disconnected return; }
zoon_
zoon_OPā€¢9mo ago
i have that in my client class
leowest
leowestā€¢9mo ago
I dont know which one is that
zoon_
zoon_OPā€¢9mo ago
clienthome.cs
leowest
leowestā€¢9mo ago
well in your code above u forgot to return here and in it u also not doing shutdown
zoon_
zoon_OPā€¢9mo ago
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
if(Utility.SocketConnected(clientSocket) && clientSocket != null)
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
return;
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
if(Utility.SocketConnected(clientSocket) && clientSocket != null)
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
return;
here this is the current code
leowest
leowestā€¢9mo ago
ok then breakpoint its probably receiving a message because otherwise it would have returned 0 and exit
zoon_
zoon_OPā€¢9mo ago
server.shutdown throws an exception
zoon_
zoon_OPā€¢9mo ago
No description
MODiX
MODiXā€¢9mo ago
leowest
and u would have to update this with
if (clientSocket == null || !client.Socket.Connected)
{
return;
}
if (clientSocket == null || !client.Socket.Connected)
{
return;
}
so it skips that if the socket is null or already disconnected
Quoted by
<@1102729783969861782> from #Clients list (click here)
React with āŒ to remove this embed.
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
how is it not connected though thats waht i dont understand im not disconnecting it yet i have a question
leowest
leowestā€¢9mo ago
probably the client disconnected
zoon_
zoon_OPā€¢9mo ago
does serverSocket.shutdown(shutdown.both) only shut down the server socket ? or during the shutdown it disconnects all connected sockets ?
leowest
leowestā€¢9mo ago
before u could reach the end of the code
zoon_
zoon_OPā€¢9mo ago
yea
leowest
leowestā€¢9mo ago
there is no server socket its 1 socket per client connection ur always running on the client socket per client
zoon_
zoon_OPā€¢9mo ago
wdym theres no server socket
leowest
leowestā€¢9mo ago
but what I mean is when u send the disconnect message to the client it closes the socket
zoon_
zoon_OPā€¢9mo ago
this is how i understand it
No description
zoon_
zoon_OPā€¢9mo ago
one socket and multiple client sockets yeah so maybe it does this before i reach the end i did that. still no luck
leowest
leowestā€¢9mo ago
foreach (...) { //send try shutdown catch close } serverSocket.Dispose(); that's my understanding
zoon_
zoon_OPā€¢9mo ago
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
if (serverSocket != null)
{
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach(Client client in clients)
{
if (client.Socket == null || Utility.SocketConnected(client.Socket)) return;
Utility.Send(client.Socket, message);
try
{
serverSocket.Shutdown(SocketShutdown.Both);

}
finally
{
serverSocket.Close();
}
serverSocket.Dispose();
}
}
}
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
if (serverSocket != null)
{
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach(Client client in clients)
{
if (client.Socket == null || Utility.SocketConnected(client.Socket)) return;
Utility.Send(client.Socket, message);
try
{
serverSocket.Shutdown(SocketShutdown.Both);

}
finally
{
serverSocket.Close();
}
serverSocket.Dispose();
}
}
}
like this ? but shouldnt the serversocket.shutdown be out the foreach loop ? like i disconnect all clients first then i shutdown the server ?
leowest
leowestā€¢9mo ago
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach(Client client in clients)
{
if (client.Socket == null || !client.Socket.Connected) continue;
Utility.Send(client.Socket, message);
try
{
client.Socket.Shutdown(SocketShutdown.Both);

}
finally
{
client.Socket.Close();
}
}
if (serverSocket != null || !serverSocket.Connected)
serverSocket.Dispose();
}
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach(Client client in clients)
{
if (client.Socket == null || !client.Socket.Connected) continue;
Utility.Send(client.Socket, message);
try
{
client.Socket.Shutdown(SocketShutdown.Both);

}
finally
{
client.Socket.Close();
}
}
if (serverSocket != null || !serverSocket.Connected)
serverSocket.Dispose();
}
small correction u cannot return in that if or u break the foreach u want to continue to the next entry until the end
zoon_
zoon_OPā€¢9mo ago
so.. why do i shutdown the client sockets but not the server socket ?
leowest
leowestā€¢9mo ago
because u dont need to u are already closing all clients, dispose will take care of the rest
zoon_
zoon_OPā€¢9mo ago
i see okay. why did i not do the client.socket.shutdown in the client class ? like here
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
if(Utility.SocketConnected(clientSocket) && clientSocket != null)
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
return;
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
if(Utility.SocketConnected(clientSocket) && clientSocket != null)
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
return;
leowest
leowestā€¢9mo ago
im confused do what?
zoon_
zoon_OPā€¢9mo ago
so when im in the foreach loop in the server_formclosing. it will send to each client a disconnected message and the client will shutdown and close itself
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
yes. isnt that what i already have here . why do i have to do it from the server and not the client itself
leowest
leowestā€¢9mo ago
server code is server code client code is client code...
zoon_
zoon_OPā€¢9mo ago
so the client shouldnt handle disconnections or disconnect itself ? i dont get it
leowest
leowestā€¢9mo ago
youre not handling it right now but you can u can also have reconnect logic
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
what you are handling is 1) when the server is shuting down 2) when you close the client there are also heartbeat logic to handle when the client suddenly disconnect there is also logic for reconnect heartbeat is the only reliable way to tell a socket is no longer in use
zoon_
zoon_OPā€¢9mo ago
i might need some logic later that if the internet on the client's pc went out it reconnects him when it's back i am not familiar with it
leowest
leowestā€¢9mo ago
that is what the heartbeat does
zoon_
zoon_OPā€¢9mo ago
but can u explain to me why we shutdown the clients and closed them FROM the server code ?
leowest
leowestā€¢9mo ago
its essentially u sending ping and hte server replying with pong so that both know each other are alive
zoon_
zoon_OPā€¢9mo ago
i see
MODiX
MODiXā€¢9mo ago
leowest
server code is server code client code is client code...
Quoted by
<@1102729783969861782> from #Clients list (click here)
React with āŒ to remove this embed.
zoon_
zoon_OPā€¢9mo ago
so the client code shouldnt have disconnects and shutdowns ? we did that when we were closing the form
leowest
leowestā€¢9mo ago
did I say that?
zoon_
zoon_OPā€¢9mo ago
we didnt send a message to the server so it disconnects us well youre saying that shutting down the client socket is server code
leowest
leowestā€¢9mo ago
no I am saying that server code is the server code. it does things on the code that is running on the server client code is client code it does things on the code running on the client they are separate things
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
they are not 1 unit orchestraded
zoon_
zoon_OPā€¢9mo ago
can you elaborate more p[lease ?
leowest
leowestā€¢9mo ago
sorry I dont know how else to put it the same way when u create a socket in the server it allocates resources, and other things it does that on the client
zoon_
zoon_OPā€¢9mo ago
i see okay okay i get it in the last line here.. why didnt you use && ? if the server exists and it's not connected
leowest
leowestā€¢9mo ago
because its one or the other not both
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
if its not null we want to dispose of it if its connected we also want to dispose of it I probably dont need the 2nd one it will probably never reach it
zoon_
zoon_OPā€¢9mo ago
yea
leowest
leowestā€¢9mo ago
u can do just
if (serverSocket != null) serverSocket.Dispose();
if (serverSocket != null) serverSocket.Dispose();
zoon_
zoon_OPā€¢9mo ago
makes more sense to me
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
if(Utility.SocketConnected(clientSocket) && clientSocket != null)
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
return;
}
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
if(Utility.SocketConnected(clientSocket) && clientSocket != null)
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
return;
}
i dont need the part where i shut it down from the client class right ? i can just stop the loop and put a message on the chatbox
leowest
leowestā€¢9mo ago
you do?
zoon_
zoon_OPā€¢9mo ago
why lol im shutting it down from both classes like this im confused why do i need to close client socket from both sides
leowest
leowestā€¢9mo ago
remove it try it and see perhaps I am wrong on that, so testing would answer that
zoon_
zoon_OPā€¢9mo ago
it didnt change anything although. the client doesnt update it's chatbox and does not post any "server has disconnected"
leowest
leowestā€¢9mo ago
it should thou
zoon_
zoon_OPā€¢9mo ago
but theres something funny
leowest
leowestā€¢9mo ago
what did u remove
zoon_
zoon_OPā€¢9mo ago
when i close the server it doesnt crash anymore when i try to send a message it throws an exception :d
leowest
leowestā€¢9mo ago
yes because ur not longer calling serverSocket
zoon_
zoon_OPā€¢9mo ago
right here
No description
leowest
leowestā€¢9mo ago
ur calling the right socket
zoon_
zoon_OPā€¢9mo ago
it says that can not append text to disposed object textbox maybe bc ive closed the form so it disposed of every object in it
leowest
leowestā€¢9mo ago
ah right because u closed the form no wait ur not closing the client that would be a server error then
zoon_
zoon_OPā€¢9mo ago
this is in the server
leowest
leowestā€¢9mo ago
yeah because you're in the process of closing the UI so u dont need to update the message on the ui from the server
zoon_
zoon_OPā€¢9mo ago
maybe ill check first if this object exists
leowest
leowestā€¢9mo ago
that was meant for the client
zoon_
zoon_OPā€¢9mo ago
before i write or invoke the event
leowest
leowestā€¢9mo ago
u can check if its Visible
zoon_
zoon_OPā€¢9mo ago
yes! to answer your question. nothing
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
leowest
leowestā€¢9mo ago
actually u can't u needto check if this.Disposing I think
zoon_
zoon_OPā€¢9mo ago
let me try
leowest
leowestā€¢9mo ago
u removed the try and catch ok
zoon_
zoon_OPā€¢9mo ago
yes
leowest
leowestā€¢9mo ago
I think its disposing let me check
zoon_
zoon_OPā€¢9mo ago
but it should atleast append text to the TB_Chatbox in my client form
leowest
leowestā€¢9mo ago
yes because you're not closing the client
zoon_
zoon_OPā€¢9mo ago
yeah im not
leowest
leowestā€¢9mo ago
so that is fine what I meant is
zoon_
zoon_OPā€¢9mo ago
it should be
leowest
leowestā€¢9mo ago
having code that updates the ui inside ServerHome_FormClosing makes no sense because at this point your ui is disposing of it self
zoon_
zoon_OPā€¢9mo ago
i dont have any code that updates ui in the server it just sends a message to the client and the client is who updates his ui
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
if (serverSocket != null)
{
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach(Client client in clients)
{
if (client.Socket == null || Utility.SocketConnected(client.Socket)) return;
Utility.Send(client.Socket, message);
try
{
client.Socket.Shutdown(SocketShutdown.Both);

}
finally
{
client.Socket.Close();
}
if(serverSocket != null) serverSocket.Dispose();
}
}
}
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
if (serverSocket != null)
{
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach(Client client in clients)
{
if (client.Socket == null || Utility.SocketConnected(client.Socket)) return;
Utility.Send(client.Socket, message);
try
{
client.Socket.Shutdown(SocketShutdown.Both);

}
finally
{
client.Socket.Close();
}
if(serverSocket != null) serverSocket.Dispose();
}
}
}
no ui stuff happening here
zoon_
zoon_OPā€¢9mo ago
i closed the server
No description
zoon_
zoon_OPā€¢9mo ago
no message on the chatbox
zoon_
zoon_OPā€¢9mo ago
now when i close the client:
No description
zoon_
zoon_OPā€¢9mo ago
i think this happens bc my client still tries to communicate with the server
leowest
leowestā€¢9mo ago
can u scroll up a bit
zoon_
zoon_OPā€¢9mo ago
and somehow the server still receives it's messages lmao
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
yeah it's still receiving somehow
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
remove the try and catch
zoon_
zoon_OPā€¢9mo ago
okay same exception
leowest
leowestā€¢9mo ago
open the call stack
zoon_
zoon_OPā€¢9mo ago
then ?
leowest
leowestā€¢9mo ago
and see where it comes from
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
line 40 ?
leowest
leowestā€¢9mo ago
did u hit connect ? again?
zoon_
zoon_OPā€¢9mo ago
no i just closed the form
leowest
leowestā€¢9mo ago
mmmm well the best here would be to add to your updateui method to check if the ui is not disposing it self before it tries to update anything
zoon_
zoon_OPā€¢9mo ago
okay
leowest
leowestā€¢9mo ago
u shouldn't be getting any messages at this point but I guess you are
zoon_
zoon_OPā€¢9mo ago
how
leowest
leowestā€¢9mo ago
and since u have a updateui in every single action
zoon_
zoon_OPā€¢9mo ago
how is the server still receiving messages
leowest
leowestā€¢9mo ago
well I dont know but look at your code the only places u have updateui are inside the actions right? so it needs to reach an action during the ui closing
zoon_
zoon_OPā€¢9mo ago
i opened the netstat -an
No description
zoon_
zoon_OPā€¢9mo ago
there are 3 servers running ?
leowest
leowestā€¢9mo ago
for that to happen ok?
zoon_
zoon_OPā€¢9mo ago
i closed the server form so it shouldnt be even listening
leowest
leowestā€¢9mo ago
it will stop listening when the serverSocket is Disposed
zoon_
zoon_OPā€¢9mo ago
and how long does that take
leowest
leowestā€¢9mo ago
as long as it takes to loop thru all the connected clients + dispose of it + the os to clean up the port
zoon_
zoon_OPā€¢9mo ago
it might take minutes ?
leowest
leowestā€¢9mo ago
for that I am unsure sorry
zoon_
zoon_OPā€¢9mo ago
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
if (serverSocket != null)
{
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach(Client client in clients)
{
if (client.Socket == null || Utility.SocketConnected(client.Socket)) return;
Utility.Send(client.Socket, message);
try
{
client.Socket.Shutdown(SocketShutdown.Both);

}
finally
{
client.Socket.Close();
}
if(serverSocket != null) serverSocket.Dispose();
}
}
}
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
if (serverSocket != null)
{
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach(Client client in clients)
{
if (client.Socket == null || Utility.SocketConnected(client.Socket)) return;
Utility.Send(client.Socket, message);
try
{
client.Socket.Shutdown(SocketShutdown.Both);

}
finally
{
client.Socket.Close();
}
if(serverSocket != null) serverSocket.Dispose();
}
}
}
shouldnt this close the socket and not make it able to receive messages ? i think i know why it's still listening hold on let me try
zoon_
zoon_OPā€¢9mo ago
also
No description
zoon_
zoon_OPā€¢9mo ago
i checked if it's disposing and it still does this
MODiX
MODiXā€¢9mo ago
leowest
actually u can't u needto check if this.Disposing I think
Quoted by
<@1102729783969861782> from #Clients list (click here)
React with āŒ to remove this embed.
leowest
leowestā€¢9mo ago
this.Disposing
zoon_
zoon_OPā€¢9mo ago
wdym by this.disposing
leowest
leowestā€¢9mo ago
as it would tell us if the form is disposing
zoon_
zoon_OPā€¢9mo ago
oh
leowest
leowestā€¢9mo ago
this refers to the Form
zoon_
zoon_OPā€¢9mo ago
i thought u meant the textbox
leowest
leowestā€¢9mo ago
but I guess u could try tb.Disposed my fear there is that tb could be null or something so I rather check the form instead
zoon_
zoon_OPā€¢9mo ago
let me try also when i close the server form it still exists in the processes under task manager i think that's why it has "listening" on netstat how do i kill it from the task manager from code
leowest
leowestā€¢9mo ago
I assume because some thread was not closed
zoon_
zoon_OPā€¢9mo ago
yes how do i check which thread is currently running and print it's name ? can i do that ?
leowest
leowestā€¢9mo ago
so u need to see which and make the loop stop can u push and send me the github
zoon_
zoon_OPā€¢9mo ago
okay
leowest
leowestā€¢9mo ago
I suppose u have no while(true)
zoon_
zoon_OPā€¢9mo ago
nope
leowest
leowestā€¢9mo ago
and they all have isrunning or something u can turn to false
zoon_
zoon_OPā€¢9mo ago
while(flag) and while(isReading) and im setting both to false at formclosing
leowest
leowestā€¢9mo ago
yeah so maybe some code blocking so I would need to take a look
zoon_
zoon_OPā€¢9mo ago
GitHub
GitHub - ZoonAttack/ChatApp
Contribute to ZoonAttack/ChatApp development by creating an account on GitHub.
zoon_
zoon_OPā€¢9mo ago
do i need to use some semaphores or smth
leowest
leowestā€¢9mo ago
not really ur not doing anything that would require a semaphore like race condition etc. all your threads are straight foward the server that doesnt close right?
zoon_
zoon_OPā€¢9mo ago
yup
leowest
leowestā€¢9mo ago
btw the disposing check worked?
zoon_
zoon_OPā€¢9mo ago
nope
leowest
leowestā€¢9mo ago
ok I will try myself in a few so it all looks good at first glance try setting up a breakpoint at
zoon_
zoon_OPā€¢9mo ago
Dispose method ?
leowest
leowestā€¢9mo ago
123 when it reaches this breakpoint, set a breakpoint on 144 102 49 and then see see if they are still running also wrap line 36 in a try catch
zoon_
zoon_OPā€¢9mo ago
okayu it would produce a socket exception correct ?
leowest
leowestā€¢9mo ago
yes when the socket is closed the serversocket that is
zoon_
zoon_OPā€¢9mo ago
lmao
zoon_
zoon_OPā€¢9mo ago
??
No description
zoon_
zoon_OPā€¢9mo ago
No description
No description
No description
zoon_
zoon_OPā€¢9mo ago
those r my breakpoints
leowest
leowestā€¢9mo ago
did u set it in the order I said and waited for the first one to hit before setting the others?
zoon_
zoon_OPā€¢9mo ago
no hold on let me try again
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
so on 102 here when i reach it i put the rest ?
leowest
leowestā€¢9mo ago
did u set all the bps at this point? if so then u hit continue
zoon_
zoon_OPā€¢9mo ago
ok i reached it
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
ill set the breakpoints
leowest
leowestā€¢9mo ago
if it hits the bp then its fine u hit continue so it goes again but it should not hit again but u set flag to false and isReading to false
zoon_
zoon_OPā€¢9mo ago
yeah i hit continue and it did nothing until i closed the client form
leowest
leowestā€¢9mo ago
no like u first set the 123 then u close it will hit that bp then u set all the other bps
zoon_
zoon_OPā€¢9mo ago
yes and i hit f11 ? to continue
leowest
leowestā€¢9mo ago
then u hit continue then it will hit the next bp etc, if
zoon_
zoon_OPā€¢9mo ago
do i hit this continue ?
No description
leowest
leowestā€¢9mo ago
102 or 144 keeps hitting it means they did not exit if they dont then they both exist and closed the threads yeah I think f11 does the same thing f11 is step out I think my bad f10
zoon_
zoon_OPā€¢9mo ago
dont u mean 102 and 49
leowest
leowestā€¢9mo ago
yes ops
zoon_
zoon_OPā€¢9mo ago
when i hit f10 no breakpoint hits
zoon_
zoon_OPā€¢9mo ago
it just gets me here lol
No description
leowest
leowestā€¢9mo ago
then it should close just fine should not remain on taskmanager that is literally the end of the app once it leaves that
zoon_
zoon_OPā€¢9mo ago
it only goes off from the task manager if i close the running solution on vs
leowest
leowestā€¢9mo ago
the Server process? weird
zoon_
zoon_OPā€¢9mo ago
yes it doesnt make sense how it's still listening even after we closed it
leowest
leowestā€¢9mo ago
I will take a look here give me a few
zoon_
zoon_OPā€¢9mo ago
maybe its because we didnt shut down the server socket ? or closed it ? but it should close when i set the flag to false
private void Listening()
{
while (flag)
{
Socket clientSocket = null;
//try
//{
serverSocket.Listen(0);
try
{
clientSocket = serverSocket.Accept();
}
catch(SocketException ex) { MessageBox.Show(ex.Message); }
Client client = new Client(clientSocket, $"Guest_{Random.Shared.Next()}");
clients.Add(client);
Thread clientThread = new Thread(() => ClientConnection(client));
clientThread.Start();
//}
//catch (SocketException soex)
//{
// serverSocket.Dispose();
// clients.RemoveAll(clients.Remove);
// UpdateUI(TB_Log, soex.Message);
//}
}
serverSocket.Close();
}
private void Listening()
{
while (flag)
{
Socket clientSocket = null;
//try
//{
serverSocket.Listen(0);
try
{
clientSocket = serverSocket.Accept();
}
catch(SocketException ex) { MessageBox.Show(ex.Message); }
Client client = new Client(clientSocket, $"Guest_{Random.Shared.Next()}");
clients.Add(client);
Thread clientThread = new Thread(() => ClientConnection(client));
clientThread.Start();
//}
//catch (SocketException soex)
//{
// serverSocket.Dispose();
// clients.RemoveAll(clients.Remove);
// UpdateUI(TB_Log, soex.Message);
//}
}
serverSocket.Close();
}
look last line
leowest
leowestā€¢9mo ago
it would not reach Main if that was the case
zoon_
zoon_OPā€¢9mo ago
if it reaches main it means it has been closed right ?
leowest
leowestā€¢9mo ago
there is indeed some thread running
zoon_
zoon_OPā€¢9mo ago
šŸ˜‚ i guess threads are mischievous
leowest
leowestā€¢9mo ago
its ok at some point u will learn async and u will be even more brainfk then now
zoon_
zoon_OPā€¢9mo ago
damn why should i learn it then šŸ˜‚
leowest
leowestā€¢9mo ago
because sockets use IO and async is much more performant for IO
zoon_
zoon_OPā€¢9mo ago
yeah probably for this problem.. idk what thread is running and why is the server still active when it shouldnt be one solution is that i should check if theres a server socket before i send any messages to it or smth what do you think
leowest
leowestā€¢9mo ago
silly why is this inside the foreach if(serverSocket != null) serverSocket.Dispose();
zoon_
zoon_OPā€¢9mo ago
huh it shouldnt lmao and i just noticed im checking twice if the socket is not null
leowest
leowestā€¢9mo ago
yeah
zoon_
zoon_OPā€¢9mo ago
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
flag = false;
if (serverSocket != null)
{
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach(Client client in clients)
{
if (client.Socket == null || Utility.SocketConnected(client.Socket)) return;
Utility.Send(client.Socket, message);
try
{
client.Socket.Shutdown(SocketShutdown.Both);

}
finally
{
client.Socket.Close();
}
}
if(serverSocket != null) serverSocket.Dispose();
}
}
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
flag = false;
if (serverSocket != null)
{
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach(Client client in clients)
{
if (client.Socket == null || Utility.SocketConnected(client.Socket)) return;
Utility.Send(client.Socket, message);
try
{
client.Socket.Shutdown(SocketShutdown.Both);

}
finally
{
client.Socket.Close();
}
}
if(serverSocket != null) serverSocket.Dispose();
}
}
look should i remove the lat if and just leave dispose ?
leowest
leowestā€¢9mo ago
so yeah this change it properly closes for me
zoon_
zoon_OPā€¢9mo ago
really ?
leowest
leowestā€¢9mo ago
yeah
zoon_
zoon_OPā€¢9mo ago
is it bc it calles dispose eeven after it's disposed ? or what or isit bc its stuck disposing 24 7 lmao infinite loop ? though it shouldnt it should exit out of the loop after 1 client bc i only have 1 client
leowest
leowestā€¢9mo ago
probably caught in an event issue where calling it in a loop or something makes it hang
zoon_
zoon_OPā€¢9mo ago
yeah probably okay so this fixed it does this also fix the updateui thing ?
leowest
leowestā€¢9mo ago
also u should use .net 8
zoon_
zoon_OPā€¢9mo ago
i dont have .net 8 is it long term support ?
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
I hope u keep your visual studio up to date at least
zoon_
zoon_OPā€¢9mo ago
no šŸ¤£ i have an update i havent done yet ill download .net 8 whats the difference ? why did u suggest that i use it
leowest
leowestā€¢9mo ago
for one all new versions of dotnet include new features and changes for 2 .net 6 EOL this year 7 too
zoon_
zoon_OPā€¢9mo ago
shit.
No description
leowest
leowestā€¢9mo ago
that is something u will eventually have to keep up with
zoon_
zoon_OPā€¢9mo ago
i see idk what eol is but sure
leowest
leowestā€¢9mo ago
end of life
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
it didnt close can u show me what changed that closed it from task manager ?
leowest
leowestā€¢9mo ago
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
flag = false;
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;

Utility.Send(client.Socket, message);
try
{
client.Socket.Shutdown(SocketShutdown.Both);

}
finally
{
client.Socket.Close();
}
}
serverSocket?.Dispose();
}
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
flag = false;
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;

Utility.Send(client.Socket, message);
try
{
client.Socket.Shutdown(SocketShutdown.Both);

}
finally
{
client.Socket.Close();
}
}
serverSocket?.Dispose();
}
zoon_
zoon_OPā€¢9mo ago
why didnt you check if its not nul ?
leowest
leowestā€¢9mo ago
? does it
zoon_
zoon_OPā€¢9mo ago
oh right
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
i had this on true instead of NOt true lmao so if it was connected it would return lmao
leowest
leowestā€¢9mo ago
honestly I would not use that code
zoon_
zoon_OPā€¢9mo ago
why ? which code u mean
leowest
leowestā€¢9mo ago
because it can't know when something closed the socketconnect the poll thing
zoon_
zoon_OPā€¢9mo ago
oh i see
leowest
leowestā€¢9mo ago
that's what heartbeat is used for
zoon_
zoon_OPā€¢9mo ago
okay ill use the normal .connected property lol
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
new exception i used exactly that and i just closed the form
if (clientSocket?.Connected != true) return;
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
if (clientSocket?.Connected != true) return;
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
i removed the comment from this and now this exception happens
zoon_
zoon_OPā€¢9mo ago
unable to read the end of the stream
No description
leowest
leowestā€¢9mo ago
well im looking so I need a moment
zoon_
zoon_OPā€¢9mo ago
okay
leowest
leowestā€¢9mo ago
ah well ofc the client doesnt work
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
huh wdym whats wrong with those two
leowest
leowestā€¢9mo ago
memorystream is empty
zoon_
zoon_OPā€¢9mo ago
oh oh shit so it's not reading any messages thats why it doesnt update the ui too only the send was working how did i miss thiss
leowest
leowestā€¢9mo ago
leowest
leowestā€¢9mo ago
yes but it was not reading probably because of that weird poll method u had otherwise it would have crashed earleir and in regards the shutdown the server does not need it just the client so server
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
flag = false;
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;
Utility.Send(client.Socket, message);
}
serverSocket?.Dispose();
}
private void ServerHome_FormClosing(object sender, FormClosingEventArgs e)
{
isReading = false;
flag = false;
ClientMessage message = new ClientMessage("Server has shutdown", ActionType.DISCONNECTED);
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;
Utility.Send(client.Socket, message);
}
serverSocket?.Dispose();
}
client
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
return;
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
return;
zoon_
zoon_OPā€¢9mo ago
all of that bc of not reading properly
leowest
leowestā€¢9mo ago
yep
zoon_
zoon_OPā€¢9mo ago
i see i see soo for further clarification if i want to handle client disconnects i send message to the server that a client is disconnecting and when the server is disconecting i send a messag to all clients that the server is shutting down so they can disconnect
leowest
leowestā€¢9mo ago
and on the client closing method also not needed
private void ClientHome_FormClosing(object sender, FormClosingEventArgs e)
{
if (clientSocket?.Connected != true) return;

message = new ClientMessage("Disconnected..", ActionType.DISCONNECTED);
Utility.Send(clientSocket, message);
isReading = false;
clientSocket.Close();
}
private void ClientHome_FormClosing(object sender, FormClosingEventArgs e)
{
if (clientSocket?.Connected != true) return;

message = new ClientMessage("Disconnected..", ActionType.DISCONNECTED);
Utility.Send(clientSocket, message);
isReading = false;
clientSocket.Close();
}
I suppose its only needed on the loop so it can tell to stop reading etc
zoon_
zoon_OPā€¢9mo ago
wdym ? how else is it gonna tell teh server that it's disconnecting
leowest
leowestā€¢9mo ago
yes
No description
zoon_
zoon_OPā€¢9mo ago
if not when the form is closing
leowest
leowestā€¢9mo ago
that is a normal procedure to gracefully terminating when u can properly close server without exceptions and notify all clients to close and they all disconnect without exceptions as well
zoon_
zoon_OPā€¢9mo ago
alright good to know
leowest
leowestā€¢9mo ago
u are did u read the code?
zoon_
zoon_OPā€¢9mo ago
you said its not needed so i was just asking why is it not needed
leowest
leowestā€¢9mo ago
I also had no issues with non-accessible ui I changed it to
if (Disposing || IsDisposed) return;
if (Disposing || IsDisposed) return;
read the code first, it is sending the message to the server
zoon_
zoon_OPā€¢9mo ago
ohh alright
leowest
leowestā€¢9mo ago
the shutdown is only need in the loop
zoon_
zoon_OPā€¢9mo ago
why ?
leowest
leowestā€¢9mo ago
read evrerything I said slowly looking at the code I've also explained it above
zoon_
zoon_OPā€¢9mo ago
also in here im closing the clientsocket but in the server im closing the client socket too im closing it twice why ? not just once
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
client.Socket.Close();
clients.Remove(client);
UpdateUI(TB_Log, $"{client.Name} {messageReceived}");
return;
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
client.Socket.Close();
clients.Remove(client);
UpdateUI(TB_Log, $"{client.Name} {messageReceived}");
return;
in the server
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
that's why I said read slowly I will be back in 20 minutes
zoon_
zoon_OPā€¢9mo ago
tyt yes i understand that this is the client side. im saying that when the client form is closing i am sending a ActionType.Disconnected to the server which in return does this : . it closes the client socket and in the client_formCLosing im closing the socket again why ?
leowest
leowestā€¢9mo ago
yes the server code is fine instead of close thou it would be better to call Dispose because like I've explained it allocates reasources both managed and unmanged that needs to be cleared said that many times now and the remove is because there is no point keeping in the list a client that has left
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.close?view=net-8.0 ur not doing it twice client code is client code... server code is server code, but I do agree that calling Dispose would be more appropriated as to not confuse u
zoon_
zoon_OPā€¢9mo ago
i think it makes more sense for the client to close it's own socket and the server to dispose the resources yeah yeah
leowest
leowestā€¢9mo ago
u would dispose on the client too when u close the app but for things like reconnect etc u can reuse it
zoon_
zoon_OPā€¢9mo ago
i see it still doesnt make sense when i close the clientsocket in client code and close it again in server code but i guess that means that the server code and client code may not have the same exact socket variable is that right ?
leowest
leowestā€¢9mo ago
Close internally calls Dispose
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
so the reason I just use Close is because I am aware of that perhaps so it can be confusing
zoon_
zoon_OPā€¢9mo ago
i see okayy thank you
leowest
leowestā€¢9mo ago
so for the client if u want to reuse the socket
zoon_
zoon_OPā€¢9mo ago
for reconnecting and stuff ?
leowest
leowestā€¢9mo ago
u might just want to call Disconnect(true) instead of the try and catch inside the loop https://github.com/ZoonAttack/ChatApp/blob/main/Client/ClientHome.cs#L83 I mean there instead of the try and catch just clientSocket.Disconnect(true); so that u can reuse the socket to try and reconnect if u want etc
zoon_
zoon_OPā€¢9mo ago
break;
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
client.Socket.Dispose();
clients.Remove(client);
UpdateUI(TB_Log, $"{client.Name} {messageReceived}");
return;
}
break;
case ActionType.DISCONNECTED:
messageReceived = br.ReadString();
client.Socket.Dispose();
clients.Remove(client);
UpdateUI(TB_Log, $"{client.Name} {messageReceived}");
return;
}
here ?
leowest
leowestā€¢9mo ago
look at the link I posted is that on the server?
zoon_
zoon_OPā€¢9mo ago
yes
leowest
leowestā€¢9mo ago
no
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
ohh i see i see thank you for the note
leowest
leowestā€¢9mo ago
the server is fine the way u did there
zoon_
zoon_OPā€¢9mo ago
ill work on the broadcasting message method now im glad it took to much time on a scale from 1 to 10 how readable/clean is my code ?
leowest
leowestā€¢9mo ago
that frigging binaryreader even I didnt look at it at first
zoon_
zoon_OPā€¢9mo ago
lmao
leowest
leowestā€¢9mo ago
its readable but could be improved a lot by decoupling all the server and client code from the ui but u dont have to worry about that now like I said complete it first then refactor
zoon_
zoon_OPā€¢9mo ago
okay ill keep that in mind youre right its better to keep it in a separate clas
leowest
leowestā€¢9mo ago
that would however require more work, u would have to create and event for the winform to use to update itself etc
zoon_
zoon_OPā€¢9mo ago
yeah im not that familiar with that yet events they confuse me
leowest
leowestā€¢9mo ago
they can be confusing but they are rather simple concept but like you're doing fine imo a lot of things takes time to get use to
zoon_
zoon_OPā€¢9mo ago
im glad thank you
leowest
leowestā€¢9mo ago
and working with sockets with a custom protocol is not exactly simple
zoon_
zoon_OPā€¢9mo ago
all of this time we havent even got to the root of this help thread šŸ’€ the clients list
leowest
leowestā€¢9mo ago
specially when u have to deal with errors that sometimes u can't control
zoon_
zoon_OPā€¢9mo ago
i hope it works now yeahh lots of exceptions
leowest
leowestā€¢9mo ago
what root?
zoon_
zoon_OPā€¢9mo ago
like the main issue i created this help thread for
leowest
leowestā€¢9mo ago
u've learned a lot of things imo from string messages that could fail to knowing the size of every message, and properly reading it... there is still 1 missing piece of code in your code which I left for u to implement which u haven't yet thou šŸ˜›
zoon_
zoon_OPā€¢9mo ago
hmm what is it i think youve said it before let me go back and see
leowest
leowestā€¢9mo ago
when the message is split into multiple packets u know the size of it, but you're only reading the first part of it
zoon_
zoon_OPā€¢9mo ago
why would it be split into multiple packets is it bc its too big ?
leowest
leowestā€¢9mo ago
mmm its a bit hard to explain but basically the MTU dictates the size of a packet so every packet will not execeed that size so if u send i.e.: 4500 and it splits at 1500 then u get 3 packets u will read the initial packet so u get ur 4 bytes to know the total size u know there is still 4496 to read u will try to read that much but Receive will only give u 1500 at one time which u can confirm with the receivedBytes so u need to keep reading till u get total amount into the buffer does that makes sense? U dont need to implement that right now, but later u can test it and see
The normal or default MTU size typically used is 1500 bytes
leowest
leowestā€¢9mo ago
that logic would happen here on both server and client
No description
leowest
leowestā€¢9mo ago
but you dont have to worry about that for now...
zoon_
zoon_OPā€¢9mo ago
private void ClientHome_FormClosing(object sender, FormClosingEventArgs e)
{
if (clientSocket?.Connected != true) return;

message = new ClientMessage("Disconnected..", ActionType.DISCONNECTED);
Utility.Send(clientSocket, message);
isReading = false;
//clientSocket.Close();
}
private void ClientHome_FormClosing(object sender, FormClosingEventArgs e)
{
if (clientSocket?.Connected != true) return;

message = new ClientMessage("Disconnected..", ActionType.DISCONNECTED);
Utility.Send(clientSocket, message);
isReading = false;
//clientSocket.Close();
}
i noticed an exception thrown bc of this last commented line the socket closes before i receive the response from the server so it gives me an exception on clientsocket.receive()
zoon_
zoon_OPā€¢9mo ago
im closing it here so i think it's fine
No description
zoon_
zoon_OPā€¢9mo ago
i think using await and async here would probably be the better option so i tell the method to wait for the server's response and all of that is that even possible /
leowest
leowestā€¢9mo ago
u should still dispose of the clientSocket there, I think the reason we had the shutdown was because it was not waiting for the message then we fixed a bunch of things and on my side it was working without the shutdown but on yours its not?
zoon_
zoon_OPā€¢9mo ago
yeah it was throwing an exception okay ill try that
leowest
leowestā€¢9mo ago
try returning the shutdown but with dispose instead because u dont get a Disconnect message on the client
zoon_
zoon_OPā€¢9mo ago
so try{clientSocket.dispose()} finally{clientSocket.close()} ?
leowest
leowestā€¢9mo ago
when ur closing the client
zoon_
zoon_OPā€¢9mo ago
well this is supposed to be sent to other clients not me
leowest
leowestā€¢9mo ago
no shutdown
zoon_
zoon_OPā€¢9mo ago
so maybe ill be like. if this is the sender client then dont send it to his socket that would be the smart way right ?
leowest
leowestā€¢9mo ago
ok let me go over this again so we are on the same page ok this code throws this is when u close the client
zoon_
zoon_OPā€¢9mo ago
yes no
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
this code throws on bytesRead = client.socket.receive because after i closed my client the same client is still trying to receive even though i closed it's socket
leowest
leowestā€¢9mo ago
ok then yes let's try to add it back
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Dispose();
}
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Dispose();
}
On the FormCLosing of the client and see if that works
zoon_
zoon_OPā€¢9mo ago
alright and i remove it from the .disconnect ?
leowest
leowestā€¢9mo ago
can u show me the code?
zoon_
zoon_OPā€¢9mo ago
its on github
leowest
leowestā€¢9mo ago
yeah I dont have the link
zoon_
zoon_OPā€¢9mo ago
GitHub
GitHub - ZoonAttack/ChatApp
Contribute to ZoonAttack/ChatApp development by creating an account on GitHub.
zoon_
zoon_OPā€¢9mo ago
i just pushed my newest code so can u check again
leowest
leowestā€¢9mo ago
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
if (clientSocket?.Connected != true) return;
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
if (clientSocket?.Connected != true) return;
try
{
clientSocket.Shutdown(SocketShutdown.Both);
}
finally
{
clientSocket.Close();
}
should be just
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
clientSocket.Disconnect(true);
messageReceived = br.ReadString();
isReading = false;
UpdateUI(TB_ChatBox, messageReceived);
clientSocket.Disconnect(true);
ok let me refresh wait this is client code
zoon_
zoon_OPā€¢9mo ago
i see disconnect(true) to reuse the socket later ? where does the program store the socket ?
leowest
leowestā€¢9mo ago
line 8? its not the same socket as in the same connection
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
its just the socket data object eetc anyway even if u do
if (clientSocket?.Connected != true) return;
if (clientSocket?.Connected != true) return;
U want the isReading = false before that loop because the thread is not dependent on the socket
zoon_
zoon_OPā€¢9mo ago
ohh right yeah okay
leowest
leowestā€¢9mo ago
šŸ‘
zoon_
zoon_OPā€¢9mo ago
and isreading before even sending the message should stop THIS client from reading back again
leowest
leowestā€¢9mo ago
I will be back in 20 minutes I just got home so ima eat my food
zoon_
zoon_OPā€¢9mo ago
okay enjoy your food
leowest
leowestā€¢9mo ago
yeah give these changes a try and lets figure out
zoon_
zoon_OPā€¢9mo ago
;p
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
but theres something i dont want it to put that big ass empty space between messages
leowest
leowestā€¢9mo ago
I dont know how u write it, I assume its sending 2 new lines instead of 1 weird that is only one newline what if u do
tb.AppendText(text);
tb.AppendText(text);
I think AppendText adds a new line or maybe your message itself had a new line I've checked the internal of AppendText it doesnt seem to add a breakline so its either u hit enter in your message box and get a double new line from your AppendText code or something else if u want u could do .Trim()
tb.AppendText($"{text.Trim()}{Environment.NewLine}");
tb.AppendText($"{text.Trim()}{Environment.NewLine}");
zoon_
zoon_OPā€¢9mo ago
okay let me tr
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
can you explain this exception for me
leowest
leowestā€¢9mo ago
>_> + try and catch
zoon_
zoon_OPā€¢9mo ago
it happens when i close the server form the only try i have is :
try
{
clientSocket = serverSocket.Accept();
}
try
{
clientSocket = serverSocket.Accept();
}
leowest
leowestā€¢9mo ago
then where is that popup coming from
zoon_
zoon_OPā€¢9mo ago
idk šŸ’€
leowest
leowestā€¢9mo ago
that is a MessageBox.Show of a exception
zoon_
zoon_OPā€¢9mo ago
i literally have no try catch other than that
leowest
leowestā€¢9mo ago
can u push the code and what were u doing whe nthat happened I will try to reproduce
zoon_
zoon_OPā€¢9mo ago
done start the server connect a client close the server after the client connects press the x on the server form
leowest
leowestā€¢9mo ago
ah ok found it
zoon_
zoon_OPā€¢9mo ago
yep
leowest
leowestā€¢9mo ago
try
{
clientSocket = serverSocket.Accept();
}
catch(SocketException ex) { MessageBox.Show(ex.Message); }
try
{
clientSocket = serverSocket.Accept();
}
catch(SocketException ex) { MessageBox.Show(ex.Message); }
U dont wnt this this is a ignore try and catch
zoon_
zoon_OPā€¢9mo ago
i didnt even see the catch šŸ’€
leowest
leowestā€¢9mo ago
try
{
clientSocket = serverSocket.Accept();
}
catch (ObjectDisposedException)
{
// Ignore
}
try
{
clientSocket = serverSocket.Accept();
}
catch (ObjectDisposedException)
{
// Ignore
}
zoon_
zoon_OPā€¢9mo ago
i should do that ?
leowest
leowestā€¢9mo ago
because Accept will throw when u terminate that's how it works that is what the docs say so when u dispose of it, it throws it doesn't peacefully exits
zoon_
zoon_OPā€¢9mo ago
oh i see didnt know that
leowest
leowestā€¢9mo ago
https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.accept?view=net-8.0
Exceptions SocketException An error occurred when attempting to access the socket. ObjectDisposedException The Socket has been closed.
zoon_
zoon_OPā€¢9mo ago
thank you
leowest
leowestā€¢9mo ago
ObjectDisposedException
zoon_
zoon_OPā€¢9mo ago
ahaa so it happens after its disposed
leowest
leowestā€¢9mo ago
might be wiser to do
try
{
clientSocket = serverSocket.Accept();
}
catch (ObjectDisposedException)
{
// Ignore
}
try
{
clientSocket = serverSocket.Accept();
}
catch (ObjectDisposedException)
{
// Ignore
}
zoon_
zoon_OPā€¢9mo ago
hmm alright
leowest
leowestā€¢9mo ago
yeah because its like a internal loop
zoon_
zoon_OPā€¢9mo ago
i see i see okay so
leowest
leowestā€¢9mo ago
I never really checked how it works internally
zoon_
zoon_OPā€¢9mo ago
let me get started with the clients list thing
leowest
leowestā€¢9mo ago
well at least it wasn't a bad exception šŸ˜›
zoon_
zoon_OPā€¢9mo ago
glad šŸ˜‚ my approach is the following: i create an "online clients" list in the client class and whenever a user joins i send his name to the user and the user adds him to the list. and when the client disconnects i send a message to the client and he removes his name is that a good approach ?
leowest
leowestā€¢9mo ago
sure, u might want to send something like Id and Username so u remove it by the id and not Username in case there are repeated usernames or u dont allow for repeated usernames
zoon_
zoon_OPā€¢9mo ago
i need to add ID first to the client class is it wise to make it readonly ? so i can only initialize it in the constructor ?
leowest
leowestā€¢9mo ago
u dont need to make it readonly
zoon_
zoon_OPā€¢9mo ago
isnt an id supposed to be some secret stuff
leowest
leowestā€¢9mo ago
public Guid Id { get; }
zoon_
zoon_OPā€¢9mo ago
or no
leowest
leowestā€¢9mo ago
this is pretty much the same as readonly in terms it can only be changed by the constructor
zoon_
zoon_OPā€¢9mo ago
i didnt even know guid exists in c# lmao is it like an integer or a string ?
leowest
leowestā€¢9mo ago
its a string kind of
zoon_
zoon_OPā€¢9mo ago
alright bet ill add the logic now ill need to create some random
leowest
leowestā€¢9mo ago
u can use an int if u prefer
zoon_
zoon_OPā€¢9mo ago
16 bit generator for the id i think short would fit it fine for now
leowest
leowestā€¢9mo ago
if ur using Guid u can just do
public Guid Id = { get; init; } = Guid.NewGuid();
public Guid Id = { get; init; } = Guid.NewGuid();
zoon_
zoon_OPā€¢9mo ago
lmfao alright good to know then i dont think i need to add it to the constructor then yeah ill just make it initialize itself whenever the client is created
leowest
leowestā€¢9mo ago
if u want an int then yeah u would need to do some trickery
zoon_
zoon_OPā€¢9mo ago
what does the init; do i never saw it b4
zoon_
zoon_OPā€¢9mo ago
okay i got it it assigns the value on object construction do you think it's smart to make a map instead of a list ? so it stores username and id ? so the index is ID and value is username ? does c# even have Map like c++
leowest
leowestā€¢9mo ago
a map?
zoon_
zoon_OPā€¢9mo ago
maybe dictionary ?
leowest
leowestā€¢9mo ago
u would make a Class
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
meant smth like this
leowest
leowestā€¢9mo ago
You can
zoon_
zoon_OPā€¢9mo ago
is it even a good idea to do that ? use the ID as key and username as value
leowest
leowestā€¢9mo ago
it would be fast to find the id... not sure it worth it for the purpose of holding just the username
zoon_
zoon_OPā€¢9mo ago
i need the username to put it on the textbox
leowest
leowestā€¢9mo ago
u already have a list with your clients
zoon_
zoon_OPā€¢9mo ago
so
leowest
leowestā€¢9mo ago
I would just add the username and id to it
zoon_
zoon_OPā€¢9mo ago
i already have that a list of client objects
leowest
leowestā€¢9mo ago
yeah I would take advantage of it
zoon_
zoon_OPā€¢9mo ago
but when i send it to the client. i want to send both the ID and username the ID to store it in a list and Username to put it on the textbox
leowest
leowestā€¢9mo ago
I mean do the way u find it will work šŸ˜› its your chat if it doesn't work we see after
zoon_
zoon_OPā€¢9mo ago
okay let me try then
leowest
leowestā€¢9mo ago
part of learning is solving the problem
zoon_
zoon_OPā€¢9mo ago
ahah yeah okay let me try uhhh hmmm ill go sleep now i got an exam tomorrow gonna do it tomorrow! @leowestlet's say i sent the client id and username as following : "ID|USERNAME" is there a way to filter it out so i put the ID in a system.guid variable and usenrame in a string ? bc .split wouldnt work here can i use binaryReader.ReadBytes to read the ID bytes and translate it to guid ?
zoon_
zoon_OPā€¢9mo ago
and is this a good idea ? the new guid(string)
No description
zoon_
zoon_OPā€¢9mo ago
the problem im thinking of is that it creates a new guid with the same ID so there are two similar ids but i guess the id im using is not directly related to the client
leowest
leowestā€¢9mo ago
you dont need to use | anymore every string u write to binarywriter comes with a prefixed size
zoon_
zoon_OPā€¢9mo ago
but im sending both Username and ID
leowest
leowestā€¢9mo ago
so you can just read it back as string just fine and then feed it to new Guid(string)
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
dont send them together bw.Write(id)
zoon_
zoon_OPā€¢9mo ago
so i can do two sends ?
leowest
leowestā€¢9mo ago
bw.Write(username)
zoon_
zoon_OPā€¢9mo ago
will the socket wait ?
leowest
leowestā€¢9mo ago
no 1 send just dont write then as 1 string
zoon_
zoon_OPā€¢9mo ago
ohh okay if i do bw.write(id) and bw.write(username) how would that work ? this is like 4 byte each
leowest
leowestā€¢9mo ago
then u can read it back as var guid = new Guid(br.ReadString()); var username = br.ReadString();
zoon_
zoon_OPā€¢9mo ago
oh ahaa so readstring reads a fixed amount of bytes ?
leowest
leowestā€¢9mo ago
no strings are different
zoon_
zoon_OPā€¢9mo ago
i see does readstring move the cursor after its done reading ?
leowest
leowestā€¢9mo ago
rrr
zoon_
zoon_OPā€¢9mo ago
what lmao
leowest
leowestā€¢9mo ago
getbytes I was using getstring lol
MODiX
MODiXā€¢9mo ago
leowest
REPL Result: Success
BitConverter.ToString(Encoding.UTF8.GetBytes("Zoon")).Replace("-", "")
BitConverter.ToString(Encoding.UTF8.GetBytes("Zoon")).Replace("-", "")
Result: string
5A6F6F6E
5A6F6F6E
Compile: 323.711ms | Execution: 20.269ms | React with āŒ to remove this embed.
leowest
leowestā€¢9mo ago
so your username to bytes is that
zoon_
zoon_OPā€¢9mo ago
thats hexa
leowest
leowestā€¢9mo ago
and then binary writer adds the size in front of it so 045A6F6F6E
zoon_
zoon_OPā€¢9mo ago
i see
MODiX
MODiXā€¢9mo ago
leowest
REPL Result: Success
BitConverter.ToString(Encoding.UTF8.GetBytes("leowest")).Replace("-", " ")
BitConverter.ToString(Encoding.UTF8.GetBytes("leowest")).Replace("-", " ")
Result: string
6C 65 6F 77 65 73 74
6C 65 6F 77 65 73 74
Compile: 337.341ms | Execution: 20.287ms | React with āŒ to remove this embed.
leowest
leowestā€¢9mo ago
as you can see the string changes based on the size
zoon_
zoon_OPā€¢9mo ago
yeah its a bit more complicated
leowest
leowestā€¢9mo ago
your name is 4 bytes mine is longer you can imagine it being string.Length in some scenarios it might be bigger because of the encoding
zoon_
zoon_OPā€¢9mo ago
got it
MODiX
MODiXā€¢9mo ago
leowest
REPL Result: Success
BitConverter.ToString(Encoding.UTF8.GetBytes("Ć©")).Replace("-", " ")
BitConverter.ToString(Encoding.UTF8.GetBytes("Ć©")).Replace("-", " ")
Result: string
C3 A9
C3 A9
Compile: 332.366ms | Execution: 20.663ms | React with āŒ to remove this embed.
leowest
leowestā€¢9mo ago
ah here is one example as u can see accent Ć© is 2 bytes for example
zoon_
zoon_OPā€¢9mo ago
interesting interesting
leowest
leowestā€¢9mo ago
but either way the binarywriter will take care of it for u on both sides since it prefixes the strings with a size
zoon_
zoon_OPā€¢9mo ago
huh ?
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
oh mb
leowest
leowestā€¢9mo ago
.tostring
zoon_
zoon_OPā€¢9mo ago
ill just send it as string
MODiX
MODiXā€¢9mo ago
leowest
REPL Result: Success
System.Guid.NewGuid().ToString()
System.Guid.NewGuid().ToString()
Result: string
3c94a738-a5f4-4b6c-80a1-f61c16251d34
3c94a738-a5f4-4b6c-80a1-f61c16251d34
Compile: 237.458ms | Execution: 18.056ms | React with āŒ to remove this embed.
zoon_
zoon_OPā€¢9mo ago
can u read this ?
leowest
leowestā€¢9mo ago
the guid? no its just random
zoon_
zoon_OPā€¢9mo ago
i see this kinda confusing and seems messy
leowest
leowestā€¢9mo ago
what?
zoon_
zoon_OPā€¢9mo ago
private void SendClientData(Client client, Guid id, string username)
{
using var ms = new MemoryStream();
using var bw = new BinaryWriter(ms);
int size = 0;
bw.Write(size);
bw.Write((short)ActionType.UPDATELIST);
bw.Write(id.ToString());
bw.Write(username);
bw.Seek(0, SeekOrigin.Begin);
bw.Write((int)bw.BaseStream.Length - 4);
client.Socket.Send(ms.ToArray());

}
private void SendClientData(Client client, Guid id, string username)
{
using var ms = new MemoryStream();
using var bw = new BinaryWriter(ms);
int size = 0;
bw.Write(size);
bw.Write((short)ActionType.UPDATELIST);
bw.Write(id.ToString());
bw.Write(username);
bw.Seek(0, SeekOrigin.Begin);
bw.Write((int)bw.BaseStream.Length - 4);
client.Socket.Send(ms.ToArray());

}
i created this new method just to send the data as two strings and now ill have to make another Broadcast() method to send it to each client the thing is i already have two methods that do this but the only difference is that here i write the guid and write the username
leowest
leowestā€¢9mo ago
I see, u mean its confusing that u have to have different methods to send and receive now because the updatelist is different
zoon_
zoon_OPā€¢9mo ago
private void BroadcastClientData(Client sender, Guid id, string username)
{
foreach(Client client in clients)
{
if (client.Socket?.Connected != true) return;

if (client == sender)
{
SendClientData(client, id, "Me");
}
else
SendClientData(client, id, username);
}
}
private void SendClientData(Client client, Guid id, string username)
{
using var ms = new MemoryStream();
using var bw = new BinaryWriter(ms);
int size = 0;
bw.Write(size);
bw.Write((short)ActionType.UPDATELIST);
bw.Write(id.ToString());
bw.Write(username);
bw.Seek(0, SeekOrigin.Begin);
bw.Write((int)bw.BaseStream.Length - 4);
client.Socket.Send(ms.ToArray());

}
private void BroadcastClientData(Client sender, Guid id, string username)
{
foreach(Client client in clients)
{
if (client.Socket?.Connected != true) return;

if (client == sender)
{
SendClientData(client, id, "Me");
}
else
SendClientData(client, id, username);
}
}
private void SendClientData(Client client, Guid id, string username)
{
using var ms = new MemoryStream();
using var bw = new BinaryWriter(ms);
int size = 0;
bw.Write(size);
bw.Write((short)ActionType.UPDATELIST);
bw.Write(id.ToString());
bw.Write(username);
bw.Seek(0, SeekOrigin.Begin);
bw.Write((int)bw.BaseStream.Length - 4);
client.Socket.Send(ms.ToArray());

}
yeah
leowest
leowestā€¢9mo ago
u can probably get away with it by customizing the clientmessage
zoon_
zoon_OPā€¢9mo ago
i might maybe adding a Sender property
leowest
leowestā€¢9mo ago
and keep just 1 broadcast for everything
zoon_
zoon_OPā€¢9mo ago
that holds both i will try this and see if it works first
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
this was mine From and To are ids
zoon_
zoon_OPā€¢9mo ago
i see i see ill see if it works and then adjust it later
leowest
leowestā€¢9mo ago
To is not always sent to its string?
zoon_
zoon_OPā€¢9mo ago
i just wanna get it to work but it seems more efficient to hold the from and to esp in ids
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
having mid terms isnt helping šŸ˜‚
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
does .readstring move the cursor after its done reading ? like does it first read the ID and then makes the start of the stream the other string ? i think im gonna be using IDS more bc if the user disconnects i wanna look for him on the onlineclients list and remove him by id
zoon_
zoon_OPā€¢9mo ago
not working šŸ˜­
No description
leowest
leowestā€¢9mo ago
ANYTHING that reads anything from the br will move it
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
so if u do br.ReadString() at the id position then next is the username
zoon_
zoon_OPā€¢9mo ago
okay
leowest
leowestā€¢9mo ago
and how do u know its not working? u only assigned it locally in your code
zoon_
zoon_OPā€¢9mo ago
its not working because the updatelist in the client code isnt being accessed
zoon_
zoon_OPā€¢9mo ago
i put a messagebox.show in it
No description
zoon_
zoon_OPā€¢9mo ago
and it didnt appear oh wait
leowest
leowestā€¢9mo ago
what is onlineClients also L
zoon_
zoon_OPā€¢9mo ago
its a dictionary wait its not working bc i didnt even start it
leowest
leowestā€¢9mo ago
:when: also also if there is 100 users in your chat and some one connects now they need to get the full list dont forge that šŸ˜‰ *ofc I wouldn't make it easier for u*
zoon_
zoon_OPā€¢9mo ago
yeah ijust realised look
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
šŸ¤£ they are both getting different lists šŸ˜­ i think ill do it a better way
leowest
leowestā€¢9mo ago
:PatrickChad:
zoon_
zoon_OPā€¢9mo ago
ill keep the list in the server or use the list made already that has the Clients now that i know what i got to do ill go take a nap šŸ˜‚
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
even though im ignoring the exception its still appearing i cant figure out how to have all clients show the same online clients it always misses like the previous online client i alrdy have the list of online clients in the server i just cant seem to send it all properly and update the textbox in the client code properly
leowest
leowestā€¢9mo ago
because that is not ObjectDisposed if u specify something in the catch it will look for that
zoon_
zoon_OPā€¢9mo ago
ahaa
leowest
leowestā€¢9mo ago
so I guess u do need to remove the () and just ignore all for it when did that one hppaned do u remember?
zoon_
zoon_OPā€¢9mo ago
what did ?
leowest
leowestā€¢9mo ago
in regards the userlist I send one complete list when they connect and just broadcast update the other clients from there u just need updates
zoon_
zoon_OPā€¢9mo ago
yeah how do i send a whole list object
leowest
leowestā€¢9mo ago
the exception
zoon_
zoon_OPā€¢9mo ago
ohh
leowest
leowestā€¢9mo ago
well u need to have a list or dictionary of users and ids u loop it and write it to the binarywriter and guess what u do after yep u broadcast and send
zoon_
zoon_OPā€¢9mo ago
so i keep writing it to the binarywriter
leowest
leowestā€¢9mo ago
u dont broadcast u just use the socket directly of the user that just connecte and send the full list
zoon_
zoon_OPā€¢9mo ago
and when i read it i loop and keep reading it
leowest
leowestā€¢9mo ago
yes u might want to write the size of the list
zoon_
zoon_OPā€¢9mo ago
and pushing it to the textbox
leowest
leowestā€¢9mo ago
and the the id /user of each user
zoon_
zoon_OPā€¢9mo ago
im confused what is the list for ?
leowest
leowestā€¢9mo ago
list dictionary whatever u are u using that have the id/username
zoon_
zoon_OPā€¢9mo ago
what i decided was im gonna have onlineclients dictionary in the server and i only send usernames to every client
leowest
leowestā€¢9mo ago
bw.Write(list.Length); loop bw.Write(id); bw.Write(user); end loop
zoon_
zoon_OPā€¢9mo ago
i see okay let me try
leowest
leowestā€¢9mo ago
well the full list of users u only send once when they connect after that u can just broadcast increments
zoon_
zoon_OPā€¢9mo ago
what if there is a client then another client connects after what do i do then
leowest
leowestā€¢9mo ago
same thing they are connected sequentially not concurrently what is the lin to your project again?
zoon_
zoon_OPā€¢9mo ago
GitHub
GitHub - ZoonAttack/ChatApp
Contribute to ZoonAttack/ChatApp development by creating an account on GitHub.
leowest
leowestā€¢9mo ago
so like right after this line https://github.com/ZoonAttack/ChatApp/blob/main/Server/ServerHome.cs#L47 is where I would send the full list to who just connected and at the same time a broadcast that, that user connected so u just use the clientSocket to send the full list to the socket that just connected and u use the broadcast to update the list with this user
zoon_
zoon_OPā€¢9mo ago
how do i update the list ? u mean i just broadcast the new user's id and username ? or what
leowest
leowestā€¢9mo ago
on the broadcast yes u do exact the way u were doing with your updatelist or w/e u had the only difference is to any user that just connected u send them individually the full list
zoon_
zoon_OPā€¢9mo ago
case ActionType.UPDATELIST:
foreach(string name in onlineClients)
{
UpdateUI(TB_OnlineClients, name);
}
case ActionType.UPDATELIST:
foreach(string name in onlineClients)
{
UpdateUI(TB_OnlineClients, name);
}
this ? i see okay i got it let me try
leowest
leowestā€¢9mo ago
whats that
zoon_
zoon_OPā€¢9mo ago
idk nvm i was trying smth lmao so right after the user connects i send him the full list
leowest
leowestā€¢9mo ago
yes using their socket
zoon_
zoon_OPā€¢9mo ago
let me see when i send the list how do i receive it from the client code ? do i keep doing username = br.readstring() ? in a loop ? it can be a loop until i < size
leowest
leowestā€¢9mo ago
sure
zoon_
zoon_OPā€¢9mo ago
since i have the message size
leowest
leowestā€¢9mo ago
but ideally u should add the list size brb food here
zoon_
zoon_OPā€¢9mo ago
alr eat well alright
leowest
leowestā€¢9mo ago
so like if u do 1 change to your updatelist u can support both when its 1 user and when its many but u need to send the amount of user before each id and user so u know how far u need to read
zoon_
zoon_OPā€¢9mo ago
im gonna do it like this
No description
leowest
leowestā€¢9mo ago
or I suppose u could check if u reach the end of the strema
zoon_
zoon_OPā€¢9mo ago
since im sending the count of elements at first
leowest
leowestā€¢9mo ago
sure that works too if u do that then u can use it to send all or just 1 user because it would handle both scenarios
zoon_
zoon_OPā€¢9mo ago
do i need if statements
leowest
leowestā€¢9mo ago
so u wouldn't need 2 separted updates
zoon_
zoon_OPā€¢9mo ago
or it will handle it on its own
leowest
leowestā€¢9mo ago
dont think so no I will be back in 30 minutes gona eat my food
zoon_
zoon_OPā€¢9mo ago
okay i think i can use this to even update the list can you check my code now ? ive made some changes i just noticed an error in sending the list i send the count as if it was the whole message's size lmao
leowest
leowestā€¢9mo ago
well that would not work
zoon_
zoon_OPā€¢9mo ago
private void SendList(Socket clientSocket)
{
using var ms = new MemoryStream();
using var bw = new BinaryWriter(ms);
int size = 0;
bw.Write(size);
bw.Write((short)ActionType.UPDATELIST);
//Writing the number of clients
bw.Write(clients.Count);
foreach(Client client in clients)
{
//Writing each name
bw.Write(client.Name);
}
bw.Seek(0, SeekOrigin.Begin);
bw.Write((int)bw.BaseStream.Length - 4);
clientSocket.Send(ms.ToArray());
}
private void SendList(Socket clientSocket)
{
using var ms = new MemoryStream();
using var bw = new BinaryWriter(ms);
int size = 0;
bw.Write(size);
bw.Write((short)ActionType.UPDATELIST);
//Writing the number of clients
bw.Write(clients.Count);
foreach(Client client in clients)
{
//Writing each name
bw.Write(client.Name);
}
bw.Seek(0, SeekOrigin.Begin);
bw.Write((int)bw.BaseStream.Length - 4);
clientSocket.Send(ms.ToArray());
}
i adjusted it
ase ActionType.UPDATELIST:
int clientsCount = BitConverter.ToInt32(buffer, 0);
for(int i = 0; i < clientsCount; i++)
{
string message = br.ReadString();
onlineClients.Add(message);
updateclientsTB(message, false);
}
break;
ase ActionType.UPDATELIST:
int clientsCount = BitConverter.ToInt32(buffer, 0);
for(int i = 0; i < clientsCount; i++)
{
string message = br.ReadString();
onlineClients.Add(message);
updateclientsTB(message, false);
}
break;
leowest
leowestā€¢9mo ago
ok that is more like it yes
zoon_
zoon_OPā€¢9mo ago
i have a question
leowest
leowestā€¢9mo ago
u dont use bitconverter there
zoon_
zoon_OPā€¢9mo ago
does bitconverter yeah i figured
leowest
leowestā€¢9mo ago
u use br.ReadInt32();
zoon_
zoon_OPā€¢9mo ago
it doesnt move the stream lmfao
leowest
leowestā€¢9mo ago
yeah
zoon_
zoon_OPā€¢9mo ago
i was just about to ask šŸ˜‚
leowest
leowestā€¢9mo ago
we only use it for the first 4 bytes because they are special
zoon_
zoon_OPā€¢9mo ago
i see i alrdy read the first 4 bytes to know the size of the whole message then i read the number of clients
leowest
leowestā€¢9mo ago
but yes that should work
zoon_
zoon_OPā€¢9mo ago
and move the stream to the beginning of the list let me see
leowest
leowestā€¢9mo ago
then u read the action, then u read the number of clients but yes the logic above sounds right with exception of the bitconveter being used there
zoon_
zoon_OPā€¢9mo ago
:yesowo:
leowest
leowestā€¢9mo ago
Also keep in mind that list does not include the server
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
well i found a bug
leowest
leowestā€¢9mo ago
unless u add a fake client to the list as the server
zoon_
zoon_OPā€¢9mo ago
i dont think mine does
private void Broadcast(Client sender, string message, ActionType type = ActionType.MESSAGE)
{
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;

if (client == sender)
{
Utility.Send(client.Socket, new ClientMessage(message.Replace(sender.Name, "me"), type));
}
else
{
Utility.Send(client.Socket, new ClientMessage(message, type));
}
}
}
private void Broadcast(Client sender, string message, ActionType type = ActionType.MESSAGE)
{
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;

if (client == sender)
{
Utility.Send(client.Socket, new ClientMessage(message.Replace(sender.Name, "me"), type));
}
else
{
Utility.Send(client.Socket, new ClientMessage(message, type));
}
}
}
leowest
leowestā€¢9mo ago
now enter with more users
zoon_
zoon_OPā€¢9mo ago
this is the broadcast method im using
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
this ME bug is so annoying šŸ˜­ its throwing me off but it's working
leowest
leowestā€¢9mo ago
what is the bug?
zoon_
zoon_OPā€¢9mo ago
let me try if a client disconnects the (me) its showing both (me) and the client's name it should only show (me) to the client that holds that username and name to the other clients check here
leowest
leowestā€¢9mo ago
u would have to modify here if username == me, add me
zoon_
zoon_OPā€¢9mo ago
let me try
leowest
leowestā€¢9mo ago
so it only changes client side
zoon_
zoon_OPā€¢9mo ago
not working
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
what u wrote push it so I cna check
zoon_
zoon_OPā€¢9mo ago
return;
case ActionType.UPDATELIST:
int clientsCount = br.ReadInt32();
for(int i = 0; i < clientsCount; i++)
{
string message = br.ReadString();
if (message == "me") onlineClients.Add("me");
else
onlineClients.Add(message);
updateclientsTB(message, false);
}
break;
return;
case ActionType.UPDATELIST:
int clientsCount = br.ReadInt32();
for(int i = 0; i < clientsCount; i++)
{
string message = br.ReadString();
if (message == "me") onlineClients.Add("me");
else
onlineClients.Add(message);
updateclientsTB(message, false);
}
break;
its pushed
leowest
leowestā€¢9mo ago
well yeah ofc it wont work ur not matching message with the actual username lol
zoon_
zoon_OPā€¢9mo ago
huh i dont get it
leowest
leowestā€¢9mo ago
message == TB_Username.Text?
zoon_
zoon_OPā€¢9mo ago
its supposed to send ME oh wait but i mean
leowest
leowestā€¢9mo ago
your username is oh
zoon_
zoon_OPā€¢9mo ago
private void Broadcast(Client sender, string message, ActionType type = ActionType.MESSAGE)
{
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;

if (client == sender)
{
Utility.Send(client.Socket, new ClientMessage(message.Replace(sender.Name, "me"), type));
}
else
{
Utility.Send(client.Socket, new ClientMessage(message, type));
}
}
}
private void Broadcast(Client sender, string message, ActionType type = ActionType.MESSAGE)
{
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;

if (client == sender)
{
Utility.Send(client.Socket, new ClientMessage(message.Replace(sender.Name, "me"), type));
}
else
{
Utility.Send(client.Socket, new ClientMessage(message, type));
}
}
}
here
leowest
leowestā€¢9mo ago
u want it to be me
zoon_
zoon_OPā€¢9mo ago
if(client == sender) send "me" so the username shouldnt even be there
leowest
leowestā€¢9mo ago
I mean u dont need to handle that server side u can handle that client side but sure
zoon_
zoon_OPā€¢9mo ago
case ActionType.USERCONNECTED:
UpdateUI(TB_Log, $"({client.Name}) has connected");
messageReceived = br.ReadString();
client.Name = messageReceived;
UpdateUI(TB_Log, $"Set Client: {client.Name}'s name to {messageReceived}");
SendList(client.Socket);

//Tell other clients a user has just joined!
Broadcast(client, client.Name, ActionType.USERCONNECTED);

Broadcast(client, $"({client.Name}) Has entered the chat! Say HI");
break;
case ActionType.USERCONNECTED:
UpdateUI(TB_Log, $"({client.Name}) has connected");
messageReceived = br.ReadString();
client.Name = messageReceived;
UpdateUI(TB_Log, $"Set Client: {client.Name}'s name to {messageReceived}");
SendList(client.Socket);

//Tell other clients a user has just joined!
Broadcast(client, client.Name, ActionType.USERCONNECTED);

Broadcast(client, $"({client.Name}) Has entered the chat! Say HI");
break;
i think its bcz of this
leowest
leowestā€¢9mo ago
hace u checked if client matched name
zoon_
zoon_OPā€¢9mo ago
` //Tell other clients a user has just joined! Broadcast(client, client.Name, ActionType.USERCONNECTED);
leowest
leowestā€¢9mo ago
if (client == sender)
zoon_
zoon_OPā€¢9mo ago
this this broadcasts to all clients. even the sender so maybe its sending ME first then its sending the username let me try nd comment this
zoon_
zoon_OPā€¢9mo ago
well now its working differently šŸ˜‚
No description
zoon_
zoon_OPā€¢9mo ago
yeah
leowest
leowestā€¢9mo ago
ah i see welll if u dont make Client IEquatable then sernder wont know how to match client
zoon_
zoon_OPā€¢9mo ago
what does that mean ohh
leowest
leowestā€¢9mo ago
its an interface that makes a contract with your class to implement 2 comparison methods
zoon_
zoon_OPā€¢9mo ago
yeah i see
leowest
leowestā€¢9mo ago
so that it knows how to compare an object of the same type
zoon_
zoon_OPā€¢9mo ago
okay ill just make it compare names
leowest
leowestā€¢9mo ago
u can do that too
zoon_
zoon_OPā€¢9mo ago
what is the function that gets the top element of the list ?
leowest
leowestā€¢9mo ago
list or dictionary? could be as simple as list[0]
zoon_
zoon_OPā€¢9mo ago
list no i meant the last element
leowest
leowestā€¢9mo ago
imagine if u could swap that 0 for the count of the list
zoon_
zoon_OPā€¢9mo ago
lmfao soo i know the fix for the (me) thing now but why does this not wor k? can u check my code now ?
leowest
leowestā€¢9mo ago
check what hte broadcast of list?
zoon_
zoon_OPā€¢9mo ago
okay i get the problem i think
case ActionType.USERCONNECTED:
UpdateUI(TB_Log, $"({client.Name}) has connected");
messageReceived = br.ReadString();
client.Name = messageReceived;
UpdateUI(TB_Log, $"Set Client: {client.Name}'s name to {messageReceived}");
SendList(client.Socket);

//Tell other clients a user has just joined!
Broadcast(client, client.Name, ActionType.USERCONNECTED);

Broadcast(client, $"({client.Name}) Has entered the chat! Say HI");
break;
case ActionType.USERCONNECTED:
UpdateUI(TB_Log, $"({client.Name}) has connected");
messageReceived = br.ReadString();
client.Name = messageReceived;
UpdateUI(TB_Log, $"Set Client: {client.Name}'s name to {messageReceived}");
SendList(client.Socket);

//Tell other clients a user has just joined!
Broadcast(client, client.Name, ActionType.USERCONNECTED);

Broadcast(client, $"({client.Name}) Has entered the chat! Say HI");
break;
here i do SendList(client.socket) which writes all clients in the Clients list and sends them to the server in a UPDATELIST message when the client receives that message it does this
case ActionType.UPDATELIST:
int clientsCount = br.ReadInt32();
for(int i = 0; i < clientsCount; i++)
{
string message = br.ReadString();
//if (message == TB_Username.Text)
//{
// onlineClients.Add("me");
// updateclientsTB("me", false);
//}
//else
//{
// onlineClients.Add(message);
// updateclientsTB(message, false);
//}
onlineClients.Add(message);
updateclientsTB(message, false);
}
case ActionType.UPDATELIST:
int clientsCount = br.ReadInt32();
for(int i = 0; i < clientsCount; i++)
{
string message = br.ReadString();
//if (message == TB_Username.Text)
//{
// onlineClients.Add("me");
// updateclientsTB("me", false);
//}
//else
//{
// onlineClients.Add(message);
// updateclientsTB(message, false);
//}
onlineClients.Add(message);
updateclientsTB(message, false);
}
it reads them and adds them to the list and updates the client TExtbox now after this finishes it goes to the Broadcast(client, client.Name, ActionType.USERCONNECTED). which tells all other clients (including the sender) the name of the client and in return the client does the following
case ActionType.USERCONNECTED:
string username = br.ReadString();
onlineClients.Add(username);
updateclientsTB(username, false);
break;
case ActionType.USERCONNECTED:
string username = br.ReadString();
onlineClients.Add(username);
updateclientsTB(username, false);
break;
it shows it on the textbox too soo now we have the Name of the client in the textbox and Me is added to the textbox so i think this is the problem one method sends (me) as it should and the other sends the name (as it should)
leowest
leowestā€¢9mo ago
so the problem is SendToAllExcept
zoon_
zoon_OPā€¢9mo ago
i think one way to avoid this is to check inside the sendlist if the client in the foreach loop has the same name as the sender so i need to pass the sender and i continue; yeah
leowest
leowestā€¢9mo ago
yep same thing
zoon_
zoon_OPā€¢9mo ago
private void SendList(Socket clientSocket)
{
using var ms = new MemoryStream();
using var bw = new BinaryWriter(ms);
int size = 0;
bw.Write(size);
bw.Write((short)ActionType.UPDATELIST);
//Writing the number of clients
bw.Write(clients.Count);
foreach(Client client in clients)
{
//Writing each name
bw.Write(client.Name);
}
bw.Seek(0, SeekOrigin.Begin);
bw.Write((int)bw.BaseStream.Length - 4);
clientSocket.Send(ms.ToArray());
}
private void SendList(Socket clientSocket)
{
using var ms = new MemoryStream();
using var bw = new BinaryWriter(ms);
int size = 0;
bw.Write(size);
bw.Write((short)ActionType.UPDATELIST);
//Writing the number of clients
bw.Write(clients.Count);
foreach(Client client in clients)
{
//Writing each name
bw.Write(client.Name);
}
bw.Seek(0, SeekOrigin.Begin);
bw.Write((int)bw.BaseStream.Length - 4);
clientSocket.Send(ms.ToArray());
}
lol i already had the sender socket as a parameter but never used it šŸ˜ wait nevermind im blind i think i need sleep
leowest
leowestā€¢9mo ago
:awesome:
zoon_
zoon_OPā€¢9mo ago
why
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
is this because count is bigger since i skipped 1 client ? ill subtract 1 from count and see
leowest
leowestā€¢9mo ago
most likely yes but ur not skipping in the foreach so I dont see that being the case ur skipping who ur sending to not the users in the list
zoon_
zoon_OPā€¢9mo ago
yes
leowest
leowestā€¢9mo ago
so the count should be right?
zoon_
zoon_OPā€¢9mo ago
idk i subtracted 1 and it worked
leowest
leowestā€¢9mo ago
I guess breakpoint there and go 1 by 1
zoon_
zoon_OPā€¢9mo ago
but now the (me) doesnt appear in the clients list
leowest
leowestā€¢9mo ago
try using Length instead of Count
zoon_
zoon_OPā€¢9mo ago
that does not exist
leowest
leowestā€¢9mo ago
it should
zoon_
zoon_OPā€¢9mo ago
it doesnt
leowest
leowestā€¢9mo ago
what is clients?
zoon_
zoon_OPā€¢9mo ago
List<Clients>
leowest
leowestā€¢9mo ago
maybe im drunk let me try weird ok
MODiX
MODiXā€¢9mo ago
leowest
REPL Result: Success
var l = new List<string> { "a", "b", "c" };
for (var i = 0; i < l.Count; i++)
{
Console.WriteLine(l[i]);
}
var l = new List<string> { "a", "b", "c" };
for (var i = 0; i < l.Count; i++)
{
Console.WriteLine(l[i]);
}
Console Output
a
b
c
a
b
c
Compile: 481.101ms | Execution: 41.888ms | React with āŒ to remove this embed.
leowest
leowestā€¢9mo ago
looks fine it shouldn't read beyond the stream
zoon_
zoon_OPā€¢9mo ago
ahhh weird
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
okay it's working after i deducted 1 from count what was causing this is
private void Broadcast(Client sender, string message, ActionType type = ActionType.MESSAGE)
{
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;

if (client.Name == sender.Name)
{
//if (type == ActionType.USERCONNECTED) continue;
Utility.Send(client.Socket, new ClientMessage(message.Replace(sender.Name, "me"), type));
}
else
{
Utility.Send(client.Socket, new ClientMessage(message, type));
}
}
}
private void Broadcast(Client sender, string message, ActionType type = ActionType.MESSAGE)
{
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;

if (client.Name == sender.Name)
{
//if (type == ActionType.USERCONNECTED) continue;
Utility.Send(client.Socket, new ClientMessage(message.Replace(sender.Name, "me"), type));
}
else
{
Utility.Send(client.Socket, new ClientMessage(message, type));
}
}
}
this commented line i was skipping it so it was sending nothing
leowest
leowestā€¢9mo ago
well if u -1 it will be missing 1 client
zoon_
zoon_OPā€¢9mo ago
yes which is the sender client
leowest
leowestā€¢9mo ago
br.Write(clients.Count) says count is int?
zoon_
zoon_OPā€¢9mo ago
yes im missing 1 client only until it accesses the USERCONNECTED part it adds it back but through the broadcast method so it shows him as (me) it seems like its a roundabout but it's working so šŸ˜‚
case ActionType.USERCONNECTED:
string username = br.ReadString();
onlineClients.Add(username);
updateclientsTB(username, false);
break;
case ActionType.USERCONNECTED:
string username = br.ReadString();
onlineClients.Add(username);
updateclientsTB(username, false);
break;
this adds (me) as a username to the list in the client code
leowest
leowestā€¢9mo ago
yeah but that is nasty in terms of missing one
zoon_
zoon_OPā€¢9mo ago
i know well i guess i can just manage it in client code better
leowest
leowestā€¢9mo ago
can u push the project with the latest I will take a look in a few
zoon_
zoon_OPā€¢9mo ago
instead of ignoring 1 do u think managing it in client code better ? okay im gonna sleep anyway got another exam tomorrow
leowest
leowestā€¢9mo ago
I think changing the me client side is the best option here I dont see why that would be a server job anyway
zoon_
zoon_OPā€¢9mo ago
yeah fair enough lmao okay its uploaded
leowest
leowestā€¢9mo ago
why there is a wild Client in the root :kekw: huh I have removed the -1 I dont have any issues there for the stream
zoon_
zoon_OPā€¢9mo ago
Weird lol
leowest
leowestā€¢9mo ago
I do get the extra me thou from the connected action thou
private void Broadcast(Client sender, string message, ActionType type = ActionType.MESSAGE)
{
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;

if (type == ActionType.USERCONNECTED && client.Name == sender.Name) continue;
Utility.Send(client.Socket, new ClientMessage(message, type));
}
}
private void Broadcast(Client sender, string message, ActionType type = ActionType.MESSAGE)
{
foreach (Client client in clients)
{
if (client.Socket?.Connected != true) return;

if (type == ActionType.USERCONNECTED && client.Name == sender.Name) continue;
Utility.Send(client.Socket, new ClientMessage(message, type));
}
}
so I guess u could just do this instead?
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
also this
No description
leowest
leowestā€¢9mo ago
remove the -1 and the condition inside
zoon_
zoon_OPā€¢9mo ago
Weird.. I swear I had it fixed lmao I'll. Check out the code Seriously Though, I can't thank you enough man You're awesome i can officially say it's working fine now ill leave it as it is for now its good enough lmao
leowest
leowestā€¢9mo ago
just missed that one thing when the packet is too big then I would say its pretty decent :catlaugh:
MODiX
MODiXā€¢9mo ago
leowest
mmm its a bit hard to explain but basically the MTU dictates the size of a packet
Quoted by
<@1102729783969861782> from #Clients list (click here)
React with āŒ to remove this embed.
leowest
leowestā€¢9mo ago
read from there to the image I wont help on this one šŸ™‚
zoon_
zoon_OPā€¢9mo ago
ahaha okay ill get to that soon but now i have a question if i wanna go by making voice chats what do you think i need to know/learn first ?
leowest
leowestā€¢9mo ago
how to access and record the mic? encoding that entails a lot of things
zoon_
zoon_OPā€¢9mo ago
how do i make a voice call basically what should i learn to be able to do that
leowest
leowestā€¢9mo ago
well part of i u already learned with the custom packet socket the principle is the same except u would be sending pcm data
zoon_
zoon_OPā€¢9mo ago
pcm i dont know that so i think ill see a video and see how people approach it but i think before that i should create "rooms"
leowest
leowestā€¢9mo ago
what u have right now could easilly add audio but real time is more complicated than just that
zoon_
zoon_OPā€¢9mo ago
do you mean voice notes ? like whatsapp ? or discord
leowest
leowestā€¢9mo ago
voice notes?
zoon_
zoon_OPā€¢9mo ago
voice messages
leowest
leowestā€¢9mo ago
yes with your current app they would be closer to voice messages depending how u receive and play it it would even feel like a live conversation
zoon_
zoon_OPā€¢9mo ago
woahh
leowest
leowestā€¢9mo ago
with a small delay
zoon_
zoon_OPā€¢9mo ago
alright interestingg ill probably need a button that starts recording from a mic and sends packets then
leowest
leowestā€¢9mo ago
GitHub
NAudio/NAudioDemo/NetworkChatDemo at master Ā· naudio/NAudio
Audio and MIDI library for .NET. Contribute to naudio/NAudio development by creating an account on GitHub.
leowest
leowestā€¢9mo ago
this might be a bit too complex for u to understand but is one example but as a very simple example u could definitively do it, if u dont try to make it real time and everything U would have to fix the packet size first thou šŸ˜› it would be as simple as u adding a new enum that sends the audio as bytes
zoon_
zoon_OPā€¢9mo ago
ill try to get the packets thing down first then
leowest
leowestā€¢9mo ago
the answer to the packets things is very simple, but I believe u should be able to solve that problem yourself
zoon_
zoon_OPā€¢9mo ago
ill read what u sent again but just a random guess the message would be too big to be sent to obviously i have to check if size is too big but the thing is if i send the size of the message when will it ever be too big ?
leowest
leowestā€¢9mo ago
just run your client write a big message like
zoon_
zoon_OPā€¢9mo ago
does it have to do with the socket.sendbuffersize ?
leowest
leowestā€¢9mo ago
BlazeBin - kwknekhlviam
A tool for sharing your source code with the world!
zoon_
zoon_OPā€¢9mo ago
what is this ohh the big message lmfao okay it sent just fine lol
zoon_
zoon_OPā€¢9mo ago
i sent all of this
zoon_
zoon_OPā€¢9mo ago
i think i just havent reached that yet
zoon_
zoon_OPā€¢9mo ago
i printed the buffer.length
No description
zoon_
zoon_OPā€¢9mo ago
is this in bytes ? so im receiving 32k bytes ? wait no im receiving 32700 int and an int is 4 bytes im receiving well over the amount which is the standard why is it not splitting ?
leowest
leowestā€¢9mo ago
u have to check bytesReceived of the actual data not the total bytes from what u send in the first 4 bytes u will see that what u send as the message size is not what bytesReceived gives u
zoon_
zoon_OPā€¢9mo ago
what's the difference ?
leowest
leowestā€¢9mo ago
$tias
zoon_
zoon_OPā€¢9mo ago
yeah how do i check the bytesRecevied of the actual data lmao doesnt the actual data get sent to bytesRead ?
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
returns
zoon_
zoon_OPā€¢9mo ago
okay i checkd that it was like 3k it didnt split or do anything
leowest
leowestā€¢9mo ago
on the bytesreceived? not the size
zoon_
zoon_OPā€¢9mo ago
yup
leowest
leowestā€¢9mo ago
its not the first 1 its the 2nd receive
zoon_
zoon_OPā€¢9mo ago
yes i checked the second
leowest
leowestā€¢9mo ago
then send a bigger message I guess your MTU might be 4096 or bigger
zoon_
zoon_OPā€¢9mo ago
lmao
leowest
leowestā€¢9mo ago
did it break now? im actually surprised it passed 3k tbh most fail at 2048 but then again I haven't messed with these stuff in a very long time and newer devices the MTU could be bigger now
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
this is the bytesRead lmao how do i know if it has been split ? is there a way that i can set the MTU to a lower limit ? so i could see it split maybe ?
leowest
leowestā€¢9mo ago
well u would get an error oh I see what might be happening can u link me ur project?
zoon_
zoon_OPā€¢9mo ago
okay
leowest
leowestā€¢9mo ago
u have a default in your switch?
zoon_
zoon_OPā€¢9mo ago
no
zoon_
zoon_OPā€¢9mo ago
GitHub
GitHub - ZoonAttack/ChatApp
Contribute to ZoonAttack/ChatApp development by creating an account on GitHub.
zoon_
zoon_OPā€¢9mo ago
ill go eat right now
leowest
leowestā€¢9mo ago
add a
default:
Debug.WriteLine("something hit");
break;
default:
Debug.WriteLine("something hit");
break;
and see on the output of vs if it says something
zoon_
zoon_OPā€¢9mo ago
lol
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
what the hell MY BAD LOL i commented the bytesRead but umm
zoon_
zoon_OPā€¢9mo ago
why is my buffer size this
No description
zoon_
zoon_OPā€¢9mo ago
lol i only pressed connect btw
leowest
leowestā€¢9mo ago
:kekw: well yeah u commented the 2nd Receive ofc it will fail
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
this is what a normal one would look like it was supposed to receive 32k only got 7 if the throw was not there it would probably fail with the stream reading out of bounds ah there we go
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
8192 so yeah needs to be a message bigger than 8.2k so it splits
zoon_
zoon_OPā€¢9mo ago
I see I can set the receiver buffer size right ? So I can try and see how I'd handle splitting Do I set the socket.receicr buffer size ? Or do I set both server and client receive size ? I have another question Is it better to adjust the sending ? Since I know the size now
leowest
leowestā€¢9mo ago
u dont need to set it just send a buffer bigger than 8.2k
leowest
leowestā€¢9mo ago
leowest
leowestā€¢9mo ago
they are both same size, and honestly I dont know how far u can adjust it up/down but 8k was default is decent imo use to be much lower
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
i think it split yeah
leowest
leowestā€¢9mo ago
if u have the throw on the server hwen it splits it will throw
zoon_
zoon_OPā€¢9mo ago
what throw ?
leowest
leowestā€¢9mo ago
the if after the 2nd receive
zoon_
zoon_OPā€¢9mo ago
i do have it it didnt throw
leowest
leowestā€¢9mo ago
well yeah u dont have it
zoon_
zoon_OPā€¢9mo ago
i do
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
put it back in and when it throws check the bytesread and the size
zoon_
zoon_OPā€¢9mo ago
the second if
leowest
leowestā€¢9mo ago
yes if it splits it will tell u
zoon_
zoon_OPā€¢9mo ago
are u sure the size of this message should make it split ?
leowest
leowestā€¢9mo ago
think so its bigger than 8.2k
zoon_
zoon_OPā€¢9mo ago
it didnt šŸ˜­
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
did u change the buffer size? no right?
zoon_
zoon_OPā€¢9mo ago
no i didnt i didnt change the receivebuffer size
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
I guess its different in your system then its on mine then
zoon_
zoon_OPā€¢9mo ago
this is the bytesRead
leowest
leowestā€¢9mo ago
then increase it copy paste twice
zoon_
zoon_OPā€¢9mo ago
it says the default for me is 8k too btw
leowest
leowestā€¢9mo ago
until it throws and u know what size is your buffer
zoon_
zoon_OPā€¢9mo ago
idk how it's different if the default is the same
zoon_
zoon_OPā€¢9mo ago
i sent this
No description
zoon_
zoon_OPā€¢9mo ago
no exception was thrown lmfao
leowest
leowestā€¢9mo ago
yeah... Its probably some info somewhere I Would have to to search and I dont have the time now, so just increasing the message size until it breaks would be the easier route
zoon_
zoon_OPā€¢9mo ago
okay whats teh website u checked the cahracters ? but hey.. if my buffer size is THAT big do i even have to handle splitting ? it looks like they made it big enough to not have that happening or maybe they are handling splitting internally ?
leowest
leowestā€¢9mo ago
CharacterCountOnline.com
Online Character Count Tool
Character Count Online is an online tool that lets you easily calculate and count the number of characters, words, sentences and paragraphs in your text.
leowest
leowestā€¢9mo ago
well apparently mine and yours is different so I would be surprised if u send it to a friend and it happens with your friend
zoon_
zoon_OPā€¢9mo ago
isnt it the same app ? or does the mtu have to do with your own isp ?
leowest
leowestā€¢9mo ago
its not the app its the pc networking anyway I will check that when I have time and figure out why yours not breaking. but I did show u above it can happen
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
here
zoon_
zoon_OPā€¢9mo ago
i think this shows something but i cant read it lmao can u read it
leowest
leowestā€¢9mo ago
they are both 1500 but perhaps some other config might have changed how it handles it
zoon_
zoon_OPā€¢9mo ago
oh
leowest
leowestā€¢9mo ago
anyway go do the voice thing u want
zoon_
zoon_OPā€¢9mo ago
is it not the bytes in and bytes out ?
leowest
leowestā€¢9mo ago
I will research on that later those are total bytes in and out from the time u turned your network on until now
zoon_
zoon_OPā€¢9mo ago
does that mean your mtu limit is 7k ?
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
that was the one I was using so I guess
zoon_
zoon_OPā€¢9mo ago
then why did it crash on 7k ?
leowest
leowestā€¢9mo ago
ĀÆ\_(惄)_/ĀÆ all I know is that it can and will split the packet
zoon_
zoon_OPā€¢9mo ago
okay i have a question
leowest
leowestā€¢9mo ago
what the exact terms are for it to happen I dont know
zoon_
zoon_OPā€¢9mo ago
is the textbox limit for characters 32k ?
zoon_
zoon_OPā€¢9mo ago
ive put 70k characters in it and it only kept
No description
zoon_
zoon_OPā€¢9mo ago
this
leowest
leowestā€¢9mo ago
default is 32767
zoon_
zoon_OPā€¢9mo ago
so i guess i cant even try out smth bigger than 32k lmao
leowest
leowestā€¢9mo ago
Think u can increase MaxLength
zoon_
zoon_OPā€¢9mo ago
what can i make it as ?
leowest
leowestā€¢9mo ago
so textbox.MaxLength = int.MaxValue;
zoon_
zoon_OPā€¢9mo ago
ohh okay
leowest
leowestā€¢9mo ago
but yeah I dont know everything about sockets either so I will look into this when I can and see because it was indeed an odd behaviors from what I know
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
holy shit šŸ’€ it didnt split
leowest
leowestā€¢9mo ago
maybe its something to do with localhost try binding to your external ip
zoon_
zoon_OPā€¢9mo ago
192.168.1.1?
leowest
leowestā€¢9mo ago
that is internal aswell but sure give it a try on that one too there is localhost 127.0.0.1, internal ips suchas the one u posted above
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
and external ips
zoon_
zoon_OPā€¢9mo ago
is this the external ?
leowest
leowestā€¢9mo ago
internal
zoon_
zoon_OPā€¢9mo ago
well idk my external ip
leowest
leowestā€¢9mo ago
Private Address Ranges Class A: 10.0. 0.0 to 10.255. 255.255. Class B: 172.16. 0.0 to 172.31. 255.255. Class C: 192.168. 0.0 to 192.168. 255.255. all these are internal
zoon_
zoon_OPā€¢9mo ago
well thats good to keep in mind but im kinda glad that no splitting is happening
leowest
leowestā€¢9mo ago
WhatIsMyIP.comĀ®
What Is My IP?
Check the IP address assigned to your device. Show my IP city, state, and country. What Is An IP Address? IPv4, IPv6, public IP explained.
zoon_
zoon_OPā€¢9mo ago
what's weird though is ive tried this before on a console application
leowest
leowestā€¢9mo ago
it will tell u your external ip
zoon_
zoon_OPā€¢9mo ago
some splitting was happening but that was because i was setting my buffer size to a fixed 1024 bytes now with the custom packet thing
leowest
leowestā€¢9mo ago
very likely your provider modem is in NAT
zoon_
zoon_OPā€¢9mo ago
it's not splitting
leowest
leowestā€¢9mo ago
so u only get internal ips
zoon_
zoon_OPā€¢9mo ago
i think i remember having nat closed
leowest
leowestā€¢9mo ago
if you are in bridge mode and have no router inbetween ur pc and you then u get a real ip if u have modem > router > pc then your router is doing the dhcp
zoon_
zoon_OPā€¢9mo ago
no i have router > pc my router is tp link do you know that brand ?
leowest
leowestā€¢9mo ago
sure if ur router is where your provider connects to and its directly connected to your pc and its set to bridge mode
zoon_
zoon_OPā€¢9mo ago
idk if it's bridge mode or not but yeah
leowest
leowestā€¢9mo ago
it would have given u a external ip not internal one aside from that u should not change it to bridge mode unless nothing else is connected
zoon_
zoon_OPā€¢9mo ago
i see
zoon_
zoon_OPā€¢9mo ago
i think it's stuck
No description
zoon_
zoon_OPā€¢9mo ago
not even opening šŸ˜‚
leowest
leowestā€¢9mo ago
http://checkip.dyndns.org/ how does nordvpn not open for u lol do u live in china
zoon_
zoon_OPā€¢9mo ago
something similar šŸ˜‚
leowest
leowestā€¢9mo ago
there u go that is your current external ip delete it šŸ˜‰
zoon_
zoon_OPā€¢9mo ago
can people hack me through my external ip ? not my internal ?
leowest
leowestā€¢9mo ago
yes it needs the external and a point of vulnerability
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
like it tells me your from somewhere in Italy for example
zoon_
zoon_OPā€¢9mo ago
let me try my external ip i see lol
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
well u wont be able to bind ot your external ip since you're behind a nat
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
u would have to create a port forward u would still bind to ur 192 ip but the port forward would redirect the requests from external access to your server in the internal network
zoon_
zoon_OPā€¢9mo ago
too much work yk what ill just handle the packet splitting without experiencing it maybe ill experience it on you šŸ˜„
leowest
leowestā€¢9mo ago
giza well u could set it to 1024 on send/receive and see if that works before u Bind
zoon_
zoon_OPā€¢9mo ago
yeah yk what ill do that and try to figure out the packet handling thingy here
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
ill now try
leowest
leowestā€¢9mo ago
šŸ‘ maybe u need to set it on the actual client socket u receive that is also worth checking
zoon_
zoon_OPā€¢9mo ago
ohh ok
leowest
leowestā€¢9mo ago
so yeah, just setting on the server under Bind
serverSocket.ReceiveBufferSize = 512;
serverSocket.SendBufferSize = 512;
serverSocket.ReceiveBufferSize = 512;
serverSocket.SendBufferSize = 512;
it throws fine for the size being too big I would expect the same behavior in your machine but I was reading that there are some optimization u can do on windows that allows it to receive a much bigger amount of packets etc https://en.wikipedia.org/wiki/TCP_tuning so that could have been one reason. so its hard to tell exactly what is contributing to your issue there on the socket ignoring the multiple packets even when I set it to a very low amount it gets more than that.
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
so as u can limiting it to 512 it still received 1006 out of the 3733 bytes it was supposed to receive in the event u decide to try and write to handle that it should allow u to do that in this way or so I hope if it does not, then just move on and write the voice part u wanted
zoon_
zoon_OPā€¢9mo ago
i dont understand this okay but you told me that if i made that voice thing and i do not handle packets being sent and splitting some packets might be dropped on the receiving machine for example if we have two different pcs on two different networks
leowest
leowestā€¢9mo ago
did u try the changes above and it does not break?
zoon_
zoon_OPā€¢9mo ago
i have not yet i just finished exams today ill try it today i think ill just get started with the voice thingy and not mind the packet stuff for now since it works im actually busy a bit preparing for the icpc if ur familiar with it its a competitive programming competition in july and i also dont wanna put too much work in a single project that is not mainly my focus. like i wont become a network guy šŸ˜„ but i had fun creating this project ive learnt alot for my next project ill actually make an automated music downloader like you give it a song name and it goes to youtube copies the link goes to any converter and downloads from it
leowest
leowestā€¢9mo ago
gl
zoon_
zoon_OPā€¢9mo ago
thank you bro youve helped me alot ive learnt so much from you. thank you
leowest
leowestā€¢9mo ago
its the rare case of iwmm
zoon_
zoon_OPā€¢9mo ago
what is iwmm
zoon_
zoon_OPā€¢9mo ago
šŸ˜‚ yeah it works on my machine šŸ˜‚
leowest
leowestā€¢9mo ago
so basically scrapping
zoon_
zoon_OPā€¢9mo ago
yeah scrapping
leowest
leowestā€¢9mo ago
kind off tables then can't discuss it here
zoon_
zoon_OPā€¢9mo ago
yeah but i have smth to say ab packet thingy
leowest
leowestā€¢9mo ago
its one of those grey areas of subject
zoon_
zoon_OPā€¢9mo ago
what is it against the law or smth lol
leowest
leowestā€¢9mo ago
scrapping yeah
zoon_
zoon_OPā€¢9mo ago
whats wrong with using scrapping to like get data from a website alot of people that create softwares for games use this method like progrms to get player info etc
leowest
leowestā€¢9mo ago
$scrape2
MODiX
MODiXā€¢9mo ago
Before scraping: 1. Read this article: https://benbernardblog.com/web-scraping-and-crawling-are-perfectly-legal-right/ 2. Use an API if one is provided, instead of scraping data. 3. Respect the Terms of Service (ToS). 4. Respect the rules of robots.txt.
Benoit Bernard
Web Scraping and Crawling Are Perfectly Legal, Right?
In this post, you'll find out more on the legal aspect of web scraping and crawling, and what possible consequences you might face.
zoon_
zoon_OPā€¢9mo ago
ill check it out
leowest
leowestā€¢9mo ago
yeah but when it comes to grey areas subject we dont discuss it because it can risk the server it self so its frowned upon generaly and if u have an API access its always better and easier anyway
zoon_
zoon_OPā€¢9mo ago
i see fair enough i had the idea of checking if bytesRead is still > than buffer.length.. that means theres some data not being put in the buffer so maybe ill loop until bytesRead is 0 and keep reading or enabling another thread to read that data exclusively until its done
leowest
leowestā€¢9mo ago
there is no point is getting another thread the read is sequential it doesnt skip and I hope u mean bytesRead < buffer.Length but yeah the idea is close to that
zoon_
zoon_OPā€¢9mo ago
isnt the bytesRead all the bytes i got from the send method ?
leowest
leowestā€¢9mo ago
except u have to use the indexes and offset in the Receive to append data to the right location of the buffer in a loop
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
its like a queue with a bunch of packets every time u do a Receive with a specific buffer size it tries to fill in as much as the Receive allows u to receive and leaves the rest in the queue
zoon_
zoon_OPā€¢9mo ago
how do i check if the queue is empty
leowest
leowestā€¢9mo ago
by keeping reading the Receive, it will always tell u how much it read so if u sent 5000 and first it reads 1500 then u know u have 3500 left to read so u just keep reading until u fill your buffer
zoon_
zoon_OPā€¢9mo ago
yeah thats why i need to check if the buffer still has available space
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
so if the bytesRead is still less than the buffer size
leowest
leowestā€¢9mo ago
and for this scenario u would use that
zoon_
zoon_OPā€¢9mo ago
the offset will be bytesRead right ? or buffer.length i mean
leowest
leowestā€¢9mo ago
the offset is where it will start writing
zoon_
zoon_OPā€¢9mo ago
yes
leowest
leowestā€¢9mo ago
so the first receive it starts at 0
zoon_
zoon_OPā€¢9mo ago
then it should start at buffer.length
leowest
leowestā€¢9mo ago
the 2nd will be 0+bytes writen from last receive
zoon_
zoon_OPā€¢9mo ago
i see i see but what does this change ? if the buffer is 1500 bytes and the bytes i received are 3000 then theres no space in teh buffer even if i offsett unless i read and process and read and process
leowest
leowestā€¢9mo ago
u know the size of the buffer when u do the byte[size] at that point u have a buffer of 3000 if u read 1500 you only filled 1500 of that buffer the rest are 0's
MODiX
MODiXā€¢9mo ago
leowest
REPL Result: Success
var buffer = new byte[1000];
Console.WriteLine(BitConverter.ToString(buffer).Replace("-",""));
for (var i = 0; i < 500; i++)
{
buffer[i] = (byte)Random.Shared.Next(1, 124);
}
Console.WriteLine(BitConverter.ToString(buffer).Replace("-",""));
var buffer = new byte[1000];
Console.WriteLine(BitConverter.ToString(buffer).Replace("-",""));
for (var i = 0; i < 500; i++)
{
buffer[i] = (byte)Random.Shared.Next(1, 124);
}
Console.WriteLine(BitConverter.ToString(buffer).Replace("-",""));
Console Output
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Compile: 432.247ms | Execution: 92.022ms | React with āŒ to remove this embed.
leowest
leowestā€¢9mo ago
so as u can see when u initialize your buffer with size its a bunch of 0's
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
once u copy part of the buffer it changes into something
zoon_
zoon_OPā€¢9mo ago
so why does splitting happen then ? if my bytes array is always [size] which is the size of the message ?
leowest
leowestā€¢9mo ago
u have to open the link to hastebin to see the full text thou the buffer u created with size is of that size because u sent a small packet telling u that but like I explained earlier and demonstrated in some images the packet may split because of either your setting in the socket, or the MTU on the machine or other configurations so imagine it breaks
zoon_
zoon_OPā€¢9mo ago
ahhh
leowest
leowestā€¢9mo ago
and u dont read the second part u now have that buffer like in that link above half filled half empty so u only have half of the message now the next packet will be the rest of the message how its suppose to read it?
zoon_
zoon_OPā€¢9mo ago
is the other packet still sent ? ohh
leowest
leowestā€¢9mo ago
it has no size on it to tell where to start or what is the actiontype so it will just break yes because like I said above its a queue of sequential data if Receives gave u bytesReceived 500 and u sent 1000 it means 500 is still in the queue to arrive that should have been placed together
zoon_
zoon_OPā€¢9mo ago
will the other packet be sent after i receive the first 500 in the buffer ?
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
not before not in between just after right ?
leowest
leowestā€¢9mo ago
it will either be instantly behind it or slightly behind
zoon_
zoon_OPā€¢9mo ago
how do i check that lmao
leowest
leowestā€¢9mo ago
yes its sequential
zoon_
zoon_OPā€¢9mo ago
if nothing is behind the packet i got then bytesRead will be 0 right ?
leowest
leowestā€¢9mo ago
if nothing is behind it will just block until more data arrives and the way u tell if u need to keep reading or not if by those 4 bytes u receive first if u receive 4 bytes telling you ur buffer is 1000
zoon_
zoon_OPā€¢9mo ago
is bytesRead is not equal to size ?
leowest
leowestā€¢9mo ago
then u keep calling Receive until u get 1000 bytesRead is always equal to how much the Receive received which may or may not be of the size of the message and when its not its because it split the packet
zoon_
zoon_OPā€¢9mo ago
yeah so i should check if the bytesRead is smaller than buffer size which is [size]
leowest
leowestā€¢9mo ago
yep and loop it until u get the full size into your buffer and ofc for that u need a bit of logic to tell how much u read, how much is left to exit the loop
zoon_
zoon_OPā€¢9mo ago
does buffer.length give me the length of the data inside it or even the 0s ?
leowest
leowestā€¢9mo ago
no buffer.Length is always size
zoon_
zoon_OPā€¢9mo ago
so the size of the whole message not whtt i received
MODiX
MODiXā€¢9mo ago
leowest
REPL Result: Success
var b = new byte[2323123];
Console.WriteLine($"before {b.Length}");
for (var i =0; i < b.Length / 2; i++)
{
b[i] = 10;
}
Console.WriteLine($"after {b.Length}");
var b = new byte[2323123];
Console.WriteLine($"before {b.Length}");
for (var i =0; i < b.Length / 2; i++)
{
b[i] = 10;
}
Console.WriteLine($"after {b.Length}");
Console Output
before 2323123
after 2323123
before 2323123
after 2323123
Compile: 479.779ms | Execution: 49.100ms | React with āŒ to remove this embed.
zoon_
zoon_OPā€¢9mo ago
i see
leowest
leowestā€¢9mo ago
yes that is why u need to do some logic between what u get from bytesRead to know remaining bytes to get and exit the loop when u got enough anyway I g2g
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
is this logical enough lol tyt
leowest
leowestā€¢9mo ago
well it wouldn't update dataRemaining as is also u can't use bytesRead as offset offset is incremental
zoon_
zoon_OPā€¢9mo ago
wdym incremental
leowest
leowestā€¢9mo ago
u have a buffer that starts at 0 so the first batch of data your offset is at 0 u write 10 to it now your offset is at 10 so next batch that comes in it will start the offset at 10 now u get 100 your offset is at 110 that is like the position it will start writting to in the buffer so everytime something is written to it, it increases the offset by that does that make sense?
zoon_
zoon_OPā€¢9mo ago
yes so i need to keep track of the bytesRead
leowest
leowestā€¢9mo ago
yes
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
like this ?
leowest
leowestā€¢9mo ago
where u have dataRemaining its just size in the Receive after the offset
zoon_
zoon_OPā€¢9mo ago
oh right so dataremaining is supposed to be size - bytesRead though right ?
leowest
leowestā€¢9mo ago
offset needs to increment after u receive not before
zoon_
zoon_OPā€¢9mo ago
okay
leowest
leowestā€¢9mo ago
flags None yes but the way u have it, it wont update either
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
because its outside the loop
zoon_
zoon_OPā€¢9mo ago
ohh mb mb ill set it to socketflags.none how
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
this is supposed to update it this is inside the loop
leowest
leowestā€¢9mo ago
I missed thathehe its right
zoon_
zoon_OPā€¢9mo ago
is this code supposed to plug everything until it matches the size into the buffer ?
leowest
leowestā€¢9mo ago
u know u can just make
int dataRemaining = size;
int dataRemaining = size;
and inside
dataRemaining -= bytesRead;
dataRemaining -= bytesRead;
zoon_
zoon_OPā€¢9mo ago
well fair enough
leowest
leowestā€¢9mo ago
buffer, offset, dataRemaining, Flags none
zoon_
zoon_OPā€¢9mo ago
No description
leowest
leowestā€¢9mo ago
same with dataRemaining needs to run after the Receive nothing happens before it
zoon_
zoon_OPā€¢9mo ago
no wait bytesRead first receives data.. the data is split bc the mtu now bytesRead < size now it enters the if so now the buffer has some data right ? bc of the receive
leowest
leowestā€¢9mo ago
that is what the loop is doing
zoon_
zoon_OPā€¢9mo ago
no i mean that the buffer has some data so the data remaining is whatever is split minus what i already have am i missing something
leowest
leowestā€¢9mo ago
doesn't matter because after u get the size u handle it all inside the loop so if all data comes in 1 or multiple packets it will handle it if ur first bytesRead is equal to size the loop will run once if its less it will run as many tims as it needs to get all no?
zoon_
zoon_OPā€¢9mo ago
here is my whole code until the loop
No description
zoon_
zoon_OPā€¢9mo ago
it will read first and if the message ive received was split it will enter the loop and read the REMAINING data so thats why i have dataremaining before the last bytesRead does that make sense ?
leowest
leowestā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
oh
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
i get it now
leowest
leowestā€¢9mo ago
u still missing 1 piece look at my curved arrow
zoon_
zoon_OPā€¢9mo ago
rightt so now this makes more sense fair enough
leowest
leowestā€¢9mo ago
And this is how I did it as a extension
public static class SocketStreamHelper
{
public static int ReceiveAll(this Socket socket, byte[] buffer)
{
var receivedBytes = 0;
var offset = 0;
var size = buffer.Length;
while (receivedBytes < buffer.Length)
{
receivedBytes += socket.Receive(buffer, offset, size, SocketFlags.None);
if (receivedBytes == 0)
throw new InvalidDataException("The connection closed unexpectedly.");
offset += size;
size -= receivedBytes;
}
return receivedBytes;
}
}
public static class SocketStreamHelper
{
public static int ReceiveAll(this Socket socket, byte[] buffer)
{
var receivedBytes = 0;
var offset = 0;
var size = buffer.Length;
while (receivedBytes < buffer.Length)
{
receivedBytes += socket.Receive(buffer, offset, size, SocketFlags.None);
if (receivedBytes == 0)
throw new InvalidDataException("The connection closed unexpectedly.");
offset += size;
size -= receivedBytes;
}
return receivedBytes;
}
}
zoon_
zoon_OPā€¢9mo ago
this makes more sense
leowest
leowestā€¢9mo ago
its essentially the same thing but prettified and in the common library
zoon_
zoon_OPā€¢9mo ago
so when do you call that receiveall ?
leowest
leowestā€¢9mo ago
and then u would use it like
bytesRead = client.Socket.ReceiveAll(buffer);
bytesRead = client.Socket.ReceiveAll(buffer);
zoon_
zoon_OPā€¢9mo ago
wait how did u connect it to the socket so u could use it under the socket class
leowest
leowestā€¢9mo ago
(this Socket socket, its a helper method that extends the socket
zoon_
zoon_OPā€¢9mo ago
ohh right right well ill keep it like that for now šŸ˜‚ let me try it ive set the send/receive buffer size to 1024
leowest
leowestā€¢9mo ago
yeah its fine im just showing mine to compare set the buffer to 128 so u dont have to sweat creating large messages anyway I g2g I will check back later
zoon_
zoon_OPā€¢9mo ago
okay tyt
zoon_
zoon_OPā€¢9mo ago
No description
zoon_
zoon_OPā€¢9mo ago
so i guess it works its handling it well wowowow i have a problem so i enabled the textbox keydown event and i am hitting enter it sends the message but it creates a new line after clearing the textbox i dont want it to create a newline how can i fix it ?
leowest
leowestā€¢9mo ago
did u do e.Handled = true?
zoon_
zoon_OPā€¢9mo ago
What is that No I didn't Ohh that tells the event handler that I'm handling it and it doesn't need to handle it ?
leowest
leowestā€¢9mo ago
it supresses it yes and but since u implemented that did u even tried to let it crash/throw first with a small packet buffer
zoon_
zoon_OPā€¢9mo ago
Wdym
leowest
leowestā€¢9mo ago
like before implenting the code u did today did u at least try to use the buffer change I mentioned to see it failed? just wondering because it wasn't failing at all
zoon_
zoon_OPā€¢9mo ago
yes it didnt fail no lmao but hey i handled packets just incase anyway i wanted to leave it as it is but i was like why not lets just handle it might learn smth
leowest
leowestā€¢9mo ago
fair I really wonder what you might have that causes it to not respect the configurations of the socket
zoon_
zoon_OPā€¢9mo ago
maybe some screwed windows settings lmao
Want results from more Discord servers?
Add your server