Clients list
I want to make a clients list for online clients connected to a server in my winform socket app
1694 Replies
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
$paste
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!
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
okay hold on ill send my current code
BlazeBin - ujwtsafxtvji
A tool for sharing your source code with the world!
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
for some reason this happens
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
for a start I would suggest u change how you're sending messages in a more structured format that u can track
hm ?
how so
your code would split this as:
so u would have 0, 1, 2
i dont even know why it is sending two messages at the same time
lmao
so you're essentially losing data
even if that was not intended u can see 1 issue
its supposed to send ONE and execute it
and then send the other one
now say you send a message that is bigger than 1024
it will break into 2 messages
yeah
true
so start by solving that by structuring a format u can recognize
well i like that format
code|<insertmessage>
but i guess it doesnt work well
what kind of format do u suggest
size
opcode
data
this is the most primitive way that its usually done
hmmm
soo if i do it by opcode
i can be like
so u know the size of the message, opcode is usually a command
MESSAGE : 1
USERNAME: 0
etc ?
and data would be whatever the command needs to use
yes it could be a simple list of enums
like that ?
sure could be that
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 ?
I dont see any message class in your code to know what it does
it does nothing
im not even using it
anyway
the message would be send as bytes
so it would need to be structured as such
size opcode data
so for example
yes ?
give me a moment busy with other stuff
okay
tyt
sorry things just got dropped at once
its okay take your time im playing anyw
and tired
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
this shit frustrates me
i dont know how to pass objects
Ah but how would I send that, we would use a combination of memorystream and binarywriter to convert it to bytes
i tried using a json serializer it bugged so hard
and send the bytes
alright ill try that
and here is where the magic happens
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
ms.ToArray()
generates something like this
and if we break it down we have
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.holy shit
š
that is alot
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
alright ill check this out
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
which is in your code, would become something like this
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
but each message wont be the same size
so it wont necessarily match the whole buffer size yk ?
that's why u read the size of the message first
do u see that i read the size
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
then I create a buffer with the appropriate size
ah i see
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
I SEEE
alrightt
let me try
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 š
š thank you
let me try
maybe u should write a separated console project
and do it there just so u understand the idea before u integrate it all
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
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
i do not know what a common library is
u mena like .h in c++ ?
header file ?
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
let me try that
ill first setup the project
server and client
https://learn.microsoft.com/en-us/dotnet/core/tutorials/library-with-visual-studio?pivots=dotnet-8-0
Create a .NET class library using Visual Studio - .NET
Learn how to create a .NET class library using Visual Studio.
using the new binary serializer
is this called like binary serializer or memory stream ?
so i can look it up on youtube
that is neither
it just helps u write stuff in binary with proper encoding etc
and primitive types to bytes
so im basically writing my data in binary
so i can send it over sockets
yep
we are going beyond low level š
its not low level thou
in terms of code
yeah i know
in terms of logic i mean
but yeah if u want to read the files your self u would need to use a hex editor
this seems too advanced
and have some understanding of types
yea
but all data is sent as bytes
so understanding how it works imo is good
true
oaky let me get to work
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 š
yeah i see that signalR does everything
and im basically trying to reimplement a whole library
not the whole library
like 5% of it
enough to make myself proud
it does a lot more than just that
how do i make reference
for projects
make two projects communicate
u right click reference in the project u want to reference it
and add project as reference
the server should have reference of the client right ?
not the other way around
no
neither server nor client need to reference each other
oohhh nvm nvm
yeah ur right
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
yea
i see
so the common is a common library
just as an example
that holds classes that are shared between client and server ?
yes
ActionType is the enum
ClientMessage is the data sent
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
sure
though ill make multiple enums since both wont have the same opcodes
or atleast the function behind them
I mean if both use the exact same thing yeah
i need to familiarize myself with async await
like this ?
well if you client and server have different actions u would have 2 different enums
yeah like this ?
or do u mean different actiontypes
mine is just this for both
i see
well i guess both would work
: short
what is this for
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
i see
okay ill use this then
its very rare that u might need more than 65K+ enums
could have been a byte too
fair fair
and in the project ref i add ref to this library ?
huh?
yes
i add the communicator
to both the client and the server ?
bw.Write((int)packetWriter.BaseStream.Length);
what does this do ? what is the packetwriter and basestream ?
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
yeah its returning
so it updates the first few bytes that translate to the size
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
how do i use the library i created after i added reference to it
through the using ?
using Comunicator;
alrighty
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));
wdym as a header of the size ?
when it does that
it removes 4 bytes from the buffer
and now it know the size of the rest
all of this just writes the type to bytes am i correct ?
so its total - 4
and it saves it in the bw ?
what does the description says
it updates the size
to the actual message size
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?
yea
then u have to - sizeof(int)
imagine your message size is 20 + the size = 24
what happens if
so in the buffer i should only store the message not the size ?
or the type
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
i see
so those 4 bytes im excluding are the Size bytes
yes
but why do i even want to know the size if im not gonna send it lmao
that size represents the rest of the data
if it includes itself in the size
then u have an array exception
hold on
ofc you send the size wdym
.
how do u think u know how much to read
.
let me keep this here
so let me go with an easier example
here when i write the size for the first time
its 00 00 00 00 right ?
yes
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
then u write the actiontype and then the data.message
leowest
Quoted by
<@1102729783969861782> from #Clients list (click here)
React with ā to remove this embed.
because of this
does this return the length of what i wrote in the byte array till now ?
yes
okay but then i also wrote the first 4 bytes of the size
Seek makes it go back to the position 0 of the byte array
if i can do that to get the whole length of the message. why do i need the first four bytes ?
so what happens if u go back to 0 and write
it will write on top of what already exists in the byte array
yes
so it updates 00 00 00 00 to actual size i.e.: 20 00 00 00
but that 20 also includes size + actiontype + message
right ?
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
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
because how do the client know that?
why cant i just write the actiontype + message and i get the length
if u just send actiontype and message how do u know the size
like this
no
wont this get the actiontype + message size
that is to write the buffer
that is not to read it
oh i see the problem now
how would it know u need to read exactly 16 if u dont send with it
// 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
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
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
i see
this is what u ended up with in the buffer
and when i read it i can read the whole message in teh buffer by excluding the first 4 bytes of the size
u dont exclude 4 bytes
.
you get the Length and remove 4 because the actiontype + message is Legth-4
so imagine u send that message
thats what i meant
yes
leowest
Quoted by
<@1102729783969861782> from #Clients list (click here)
React with ā to remove this embed.
what do u think that happens here?
there is 20 bytes in the socket
i create a sizeBuffer that holds 4 bytes. which where the size bytes would fit
20 00 00 00
4
yes it takes 4 bytes from the socket
so ur left with 16 bytes
then i receive the whole message in the receiveBytes
yes
leowest
Quoted by
<@1102729783969861782> from #Clients list (click here)
React with ā to remove this embed.
but now here is the problem
var size = BitConverter.ToInt32(sizeBuffer, 0);
is still 20
what happens if u try to read 20 again?
does it receive 4 bytes from the beginning or from the end ?
always the head
.
so the message ?
or the size
the head is the part from the left right ?
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?
exception probably
exactly
im trying to read more than what i received
that is why u need to remoe 4 from the Length
do u understand it now?
yes
so i need to send the size so the server knows the actual size of the message
yes
so at first i receive 4 bytes which are the size bytes
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
bw.Write((int)packetWriter.BaseStream.Length);
is this packetwriter integrated in memorystream ?
the binarywriter writes to the memorystream
and under the hood they both inherit from stream
im triying to use the packetwriter its unkown
ah my bad
its just bw
or ms
let me check
yeah its just bw
its bw
I forgot to rename it sorry
yeah
its okay
was writing the example in a hurry heh slip
all good bro
thank you
so this just gets the message, writes it in bytes to the memoryStream
now u have to add to it -sizeof(int)
like we talked
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
yes
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 ?
yes
no
u do send 20 bytes
yes i know
but the message is only 16
im talking ab when i read the message only
we just talked about how its read
u first read 4 bytes
those are the sizes's bytes
yes
then i use those and assign them to the buffer so it has the actual size
of the message
yes
after i do this
do i send it directly without Encoding.utf8.getBytes ?
it already encodes the string
that is why u define it in the binary writer
so i can send it to the socket right away ?
yeah
that means when u do bw.Write(data.Message) it will already be utf8 encoded
yes u can
like this ?
so now the data sent to the server is the size + actiontype + message
let me try and read it
do i do the reading on two parts ?
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 ?
yes
u can't read the message if u dont know the size
that is the whole point
where does the data stay until i read it ?
if its not in the buffer. then where is it
it stays in the socket
how
it has no buffer to stay in
Receive(buffer)
means u want the socket to give u a buffer of that size
period
i see
i thought it means. im receiving the bytes TO that buffer
which is MY buffer
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
sooo the other 16 bytes is kept in another buffer made by the socket ?
sure u can think of it that way
alright
wait
is it kept in the CLient socket or the Server socket ?
every client u listen to u are essentially having a socket between the server and client there
yes
i know that
so it will be ONE server socket that was open for that specific client
using var br = new BinaryReader(incomingPacketStream); what does the incomingpacketstream do ?>
did I forgot to rename that?
its just the memorystream
memorystream holds the buffer and feeds the reader with it
ah i see
so it uses the memorystream as a buffer to read bytes into it
?
u give the buffer to the memorystream so the binary can acess the stream
yes
read bytes from it
from it ? even though im making a new memorystream ?
wont it have no data ?
oh nvm
i didnt read properly
and ofc I forgot to rename incomingPacketStream to ms
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 ?
yes
and readstring returns the rest of the bytes as string right ?
like translates it to string
so binarywriter writes the length of the string along with it
so it know how much to read
hmm okay
does it also write it at the beginning
4 bytes aswell ?
yes its a prefixed length
https://learn.microsoft.com/en-us/dotnet/api/system.io.binarywriter.write?view=net-8.0
sick!
did u just make that lmao
why does it do that ?
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
š
that was fast nice
looks like it connected and disconnected?
yeah
weird
can u see why ?
bc i cant lmao
shouldn't this be false?
looks fine maybe the issue is on the server?
lmfao
yeah
here is the server
it will exit the console
and close the server
oh
bruhh
ill make the main thread sleep
nvm that would be dumb
how can if ix this hmm
can u $paste it to the site below
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!
discord embed files suck
and I will brb
alright tyt
BlazeBin - kweeklvechug
A tool for sharing your source code with the world!
i even tried to make it join so it waits for the new thread to terminate
soo the main thread paused
but it still disconnects
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
fair
let me try
why do u have the serverSocket.listen outside the while loop
should it be outside the while
still connects and disconnects
check the docs and see what it does
ohh okay
yes but the console no longer exits now right
i mean its still open
theres still a while true loop running
so we solved 1 problem
now we need to look and find out why its disconnecting
give me a moment
i think its here
in this method
int bytesRead = 0;
this is the problem
i had that in my winform app
it was fine i think
hold on let me check
I will brb and explain
okie
yeah i have it lik that in my prev app
weird
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
i see
alrighty let me see
but anyway that is not the issue do u have github
reading code like this is making my head spin
YEAH
ill push the code on github
hold on
gimme some time
yeah that would be easier so the whole picture
alright give me some time
I need to go out for a few minutes too I should be back in 40 minutes or so
okay that should be fine!
thank you bro
oh my god
the solution got deleted
š
:catlaugh: how
i changed to the master branch and it gave me an error
now all of a sudden my solution is not there
u can change back to master etc
u can revert changes
as long as u have no deleted it your self
i cant open the solution
to revert changes
do from the command line
git also works from the command line
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
command prompt
okay whats next
then cd into the folder
then
replace master to whatever it needs to be
the folder is empty
then u must have deleted the entire folder
oof
bro
i didnt
yikes
that is beyond git repair
well
are u sure ur not in the wrong folder?
atleast i have my files here
the client and server
it should have a .git dir
no. this is the solution folder
ill just make a new project rn
oof
also. if i have ongoing work. should i push it to a new branch other than main and master ?
well u have to have manually hit delete
to delete the folder thou
the funny thing is i didn't
what were the last things u did then
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 ?
but u have no .git folder?
yep
weird
normally i twould be like that
if .git does not exist it means it was manually deleted
ill just make a new project
yikes
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
okay we are back
now let me put it on github
what are those files ?
i see them often
in my git change
u forgot to add gitignire file
when u create it
dotnet new gitignore
where do i write that ?
u open the command prompt
go to the folder with the command prompt
and type it
i added it
the project
GitHub
Projects/ChatApplicationTest at ongoing Ā· ZoonAttack/Projects
Projects i've been working on. Contribute to ZoonAttack/Projects development by creating an account on GitHub.
wait
it literally
uploaded like 2 files
wtf
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
what
i have a gitignore file
huh no like
like this ?
i used the dotnet new gitignore in the visual studio windows powershell
yes but u did not create the git in that folder
that is the problem
i cloned a repo from github
and copied the file into it
and pushed it
create a blank solution
add git to it
then add projects
what projects
you mean those projects in the screenshot ?
whats wrong with the way i did it ?
cant find the create git repo
because the way u did u will have to create multiple github repositories
instead of having 1 repository with your entire solution
so youre sayin i should create one solution that has multiple projects ?
normally that is how u do it
lets say i have multiple projects that have nothing to do with eachother
i should keep them under 1 solution ?
yes what si wrong with that?
that is how it usually works
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
no
that is the exact purpose of the solution
alright let me see
.
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.
"which are usually related to each other." yeah
which is your case š
yep
.
u right click the solution
i did that
theres already a git repo opened
how do i close it
do i delete the remote ?
well I suppose because u created it on the project
i created a different blank solution
ok
and it does nto show?
nope
there is an opened git repo
u probably placed it inside a folder that already had git
yep
hold on
i deleted the .git folder
and it still doesnt show to create a new repo
u prob need to close visual studio and open again
yep
okay ill create a new repo
when something simple becomes so complex š
i created it
woohoo
let's goo
now i just add the projects right ?
yep
and the projects will by default already be covered by git
if i change this
does it cause any problems later ?
for the repo ?
why would u want to change that?
because i have 2 projects. client and server
sure
and i need both to start
together
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
how is there two repos
wtf
ah maybe u set it to the same github repository?
i deleted the one called projects
before i made a new one
normally it looks like this
if nothing to commit
yea
lmao
what is even happening
why is it so messy
ah I see u have 2 branches
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
well branches are the same repo
its like a state and u swap between states as needed
GitHub
Projects/ChatApplicationTest at ongoing Ā· ZoonAttack/Projects
Contribute to ZoonAttack/Projects development by creating an account on GitHub.
well anyway heres the code
but why did u create a branch
k will check in a few
because i thought its better
to have another branch where i commit ongoing projects
that havent been finished yet
well u first develop
once project is in a stable state
good
then when u create a branch to add a new feature
yeah thats why i made another branch
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
so should i commit to the main branch only ?
yeah use the main branch only until u have something ur satisfied with
and then what
unless you had a crazy idea that involves rewriting the whole code
u dont need a branch
alright ill delete it later
i have to go sleep now got uni tom
alright
check the code out please and tell me if u figured out anything new that's beencausing this error
cheers
as silly as it sounds ur not doing anything with the client socket, ur not passing it to the thread to use
Yikes
Mb
no worries been at it for too long plus the git issues
ookayy
so the sending messages works
that's great
now i can integrate it in my project
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
normally u create a github repo per solutions
its also good to have github because it shows people your progress etc
what u know
do you mean that i create a repo for every project ?
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 ?
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
does this look confusing
:d
with a readme to tell me waht each folder is yeah
the name doesn't always translate intent
yeah fair fair
i think im redoing the whole project at this point lmao
up to you
there was a lot of information going on š
i suddenly hate github
why is it so hard to push a project lol
hard?
its 1 button
its messy
how so?
i keep pushing and it pushes only files not even my projects
did u forgot the gitignore again
no i added it to all projects
š
or should it be in the solution only
u dont add it to all projects
u just add it to the solution
yk what
ill create a new solution
from the beginning
lol
ill make it from scratch
with the new things ive learnt
lets hope i dont have to do that again
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
it confuses me even more
through the command line
i just know git commit
and git push .
lmao
$gitstarted
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 sheetLearn Git Branching
An interactive Git visualization tool to educate and challenge!
cheers
the last link is a good practice
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
it would belong to the server project
yeah i figured
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
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
empty
maybe restart vs?
make sure your code builds
it's not even generating
code
and the designer is not broken as well
in the .cs of the designer
yeah then restart vs
okay!
$vsdrunk
* 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 vsoho kay
so my client form has nothing now
it's empty
resetted š
ugh
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?
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
no because I often commit
so I dont lose my stuff
i see
I implement a feature, commit
I fix a bug commit
bet bet
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
ohh smart smart
okay ill commit more
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
seems complicated
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
also
var size = 0;
this is naturally int right ?
so 4 bytes
i seeif 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
what about the A
A is addition so it wont show anything new but the file itself
i see
so here I added that part that has a green square around it
ohh
makes sense
i have a question
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
can i use the first message and use it again after sending it ?
like this
or it wont matter if i create new instances of the clientMessage class ?
the moment u accept the socket u know its connected
i see
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
i have it that u need to put a username
the client message is suppose to be new instances
i see
alright
but if u send modify and send
it wont affect it because its not used anywhere else
so u could technically do that too
which is more efficient ?
in terms of memory
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
yeah
it wouldnt know which instance
to fire
because u would effectively change the content of it
its not which to fire
it would just be the same
i see
well ill keep it simply one instance for now
if i face any problems ill change it
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
lmao yeah
i get it
would this be a proper way to give my clients initial name until i receive the USERNAME message from the client socket ?
they all would be named Guest
yes
that's fine
may i see your random guest number generator ?>
Name = $"Guest_{Random.Shared.NextInt()}";
wat's random.shared ?
Random is a class that generate random numbers
Shared is an instance of it
i see
its like singleton ?
so u dont have to initialize it, and can use it directly
the instance
sort of [
i see
theres only NextInt64 though
lmao
isnt that too big
just Next then
can i use the clientMessage class of my class library(communicator) to send messages from server to client
?
BlazeBin - jcllryauuvfj
A tool for sharing your source code with the world!
do you have any comment on this so far ?
anything i could improve ?
isn't that what ur doing?
yes
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)
honest opinion but at the same time tell me if im doing smth wrong
this
to see if it's still connected
u know clientSocket have a .Connected property right?
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
I dont see how that will help u
what is that ?
unless you're actively sending data between the 2 i.e.: a heartbeat
this happens when i connect
i see
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
it actively refused it
i think i need to change the port
am i correct ?
i see
alright
is the server running?
is the ip and port right?
yes the server is running
do you know the command prompt command
that checks all active ports ?
netstat -an
it's listening
dont use
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:
Can be just
same for binaryreader/writer
Instead of
Why not just use
It reduces yet another nested if from the code.
i see i see
good comments ngl
thank you bro
i think for the while
hmm
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
it wouldnt hurt to know
and instead of bloating your forms with all that code u would call for example
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
okie thank you for noting that
for my do while
what variable should i put in it ?
to check
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
what appropriate method ?
would u call before
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
i edited it
this is the server
and this is the client
if u do not return on that if it will run all the code under it
i see
yeah mb
also. when i allow my server through the firewall
which .exe should i put ?
the one in debug ?
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
yes
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
i see
new error
your message is not what ur expecting
hover your mouse on bytesRead
it's 8
also how do u read it
if ur memorystream is empty
...
how is it empty
oh shit
wait
š
okay i know the fix to this error
i need to invoke that method on the ui thread
yes
umm
what is the textbox passed as
like what is it's type ?
if i want to pass it as a parameter
im not following maybe u want to show me what you're doing instead
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
I dont think that should be a utility method since its tied to winform
i see
yeah
u would have to reference winform into the library, just to use the type of the textbox
not a good approach imo
ill just use it like this
in my client form code
and server form code
sure
yay
ayee
how do i check if my server socket is still running ?
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
what do you mean by heasrtbeat
why does it say this
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
now this
well u only start that thread
after u connect to the server
never before
so that should be a problem
yes
how
did u try to reconnect?
and that is what that error came from?
nono i just connected
and i closed the client form
ah that's on the server
ok
so what happens there is
this right here should annoounce in the log that someone has disconnected
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
i see i see
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
yeah im on that
so this is more appropriate ?
should i remove this line and just put all what's in it in the disconnected part ?
you would have something like this
and you would also wrap the Send part too
i see
how about this ?
$paste
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!
stuff are really messy now
im trying to handle disconnections when the form closes
but its messy
ill send u the code
BlazeBin - bdmrrlymdjrg
A tool for sharing your source code with the world!
this happens when i close the client form
this happens when i close the server form
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
only that one line ?
okay
you mean i cant terminate it unles im in async mode ?
this one I already explained above
u do this
but i did do that
ah that is on the client side when server closes?
this is on th client side when i close the client form
this one I mean
so yeah u would add an event to your form
I think FormClosing its called
i did
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
yeah
I will say in a bit the page is having a hard time to load your code
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
i think i need to use await
no
Send is blocking
it will not go to the next code if it has not executed
then why did it work when i commented the line
lmao
weird
commented what line?
clientSocket.Close();
this
ah u mean the message was not reaching the server?
yeah maybe the socket for some reason closes before the message is received
and processed and executed
ah there we go
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.
ohh
okay let me try
so i call the shutdown before the close ?
exactly as the example above
i didnt know c# has finally{}
lol
well it is
try
{}
catch
{}
finally
{}
yes
its in python too
so the .shutdown ensures that all messages being sent are received first ?
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.
okay soooo
š
are u sending something to the client after its closed
no
to the client ?
wait
no im not
ah my bad that ist he server
this is my form closing
im not sending anything
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
Oh mb
Also
Won't the finally block execute anyways ?
Even if there was an exception caught ?
it will but why wrap unnecessary code in it
Is that bad
it can be
imagine what u were doing before
Soo it won't trll me what's wrong with my code if I put it in the try
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
Yeah fair enough lmao
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
I'll have to put a breakpoint yo see
To
I'm supposed to handle things on the server side right m
?*
ah yes ur not returning
Oh right
change break to return;
Ok
and close the socket
ur not closing it
Which socket ?
But I'm closing it from the client home page form
client.Socket
.
Client socket .close
client code is client code
server code is server code
So they r not the same socket ?
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
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
i have problems with reading docs š
but ill try
so like this ?
yep
still threw the same exception
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;
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
that is wrong
it doesnt do that and instead throws exception
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
where do u want me to put the brekapoint at
then something is wrong in your code
oh wait nvm
i put the breakpoint in the server
u can put the breakpoing inside the disconnect
not the client
it is in the server
that error is in the server no?
i did put it there
no
in the client
i saw it wrong
ah me too I guess
okay
so what happens is
it goes to the Send(message) method
completes it
then throws the exceptin right away
ok so it throws because shutdown canceled the receive method
so u might need to do
If (bytesRead == 0) return;
i see
alright
right after the first receive method
yes
okay it worked
because what happens on the client is 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
yeah true true
understood
shutdown stops receiving so it received 0
a lot of small details
it returns 0
not receives š
i see š
okie
this happens when i close the server form
well the server is more complex
i see š
u have to iterate over all the open clients
and close all sockets ?
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
i see i see
yeah
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
so i loop over my clients list
disconnect all of them ?
and i dispose the server ?
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
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
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
i see
before turning off
okay i will do that
what should the clients do when i tell them the server is disconnecting ?
the path of properly coding is arduous š
yeah..
but its fun
well u would stop the loops, close the socket and maybe post a message to the textbox saying server disconnected
okay fair
and u might also need to do the same thing u did on the receive for the bytesReceived 0
i will do that
its the pretty much the same proccess of when a client disconnects but reversed
i will do that tomorrow i have to sleep now
got exam tom
and u would have to update this with
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 š
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
the above is client not server
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
`
this is in the client
i face this exception in my send method
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
why?
why what
I told u is the same process
shutdown, close
also check before if its not null and connected
okay
wrong event ServerHome_FormClosed?
why Environment.Exit(0);?
also return not break
i changed that i just forgot to send it
ok and why Environment.Exit(0);?
i wanted the app to close if the server is turned off
but i deleted it
that is not closing the app
that is killing it half way
huh ?
š
i see
i didnt know
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
oaky
.
depends where its called no?
u moved it to the utility library
this exception is fixed now. im facing this
I suppose that is the same issue as before
this is in the client
u disconnect
yeah
does not return the loop
and forget to do the
if (bytesReceived == 0)
{
// app disconnected
return;
}
i have that in my client class
I dont know which one is that
clienthome.cs
well in your code above u forgot to return
here
and in it u also not doing shutdown
here
this is the current code
ok
then breakpoint its probably receiving a message
because otherwise it would have returned 0
and exit
server.shutdown throws an exception
leowest
and u would have to update this with
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.
how is it not connected though
thats waht i dont understand
im not disconnecting it yet
i have a question
probably the client disconnected
does serverSocket.shutdown(shutdown.both) only shut down the server socket ? or during the shutdown it disconnects all connected sockets ?
before u could
reach the end of the code
yea
there is no server socket its 1 socket per client connection
ur always running on the client socket per client
wdym theres no server socket
but what I mean is
when u send the disconnect message to the client
it closes the socket
this is how i understand it
one socket and multiple client sockets
yeah so maybe it does this before i reach the end
i did that. still no luck
foreach (...)
{
//send
try shutdown catch close
}
serverSocket.Dispose();
that's my understanding
like this ?
but shouldnt the serversocket.shutdown be out the foreach loop ?
like i disconnect all clients first then i shutdown the server ?
small correction u cannot return in that if or u break the foreach
u want to continue to the next entry until the end
so.. why do i shutdown the client sockets but not the server socket ?
because u dont need to u are already closing all clients, dispose will take care of the rest
i see
okay. why did i not do the client.socket.shutdown in the client class ?
like here
im confused do what?
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
yes
yes. isnt that what i already have
here
.
why do i have to do it from the server and not the client itself
server code is server code client code is client code...
so the client shouldnt handle disconnections or disconnect itself ?
i dont get it
youre not handling it right now but you can
u can also have reconnect logic
i see
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
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
that is what the heartbeat does
but can u explain to me why we shutdown the clients and closed them FROM the server code ?
its essentially u sending ping and hte server replying with pong
so that both know each other are alive
i see
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.
so the client code shouldnt have disconnects and shutdowns ?
we did that when we were closing the form
did I say that?
we didnt send a message to the server so it disconnects us
well youre saying that shutting down the client socket is server code
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
i see
they are not 1 unit orchestraded
can you elaborate more p[lease ?
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
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
because its one or the other not both
i see
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
yea
u can do just
makes more sense to me
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
you do?
why lol
im shutting it down from both classes like this
im confused
why do i need to close client socket from both sides
remove it
try it
and see
perhaps I am wrong on that, so testing would answer that
it didnt change anything
although. the client doesnt update it's chatbox and does not post any "server has disconnected"
it should thou
but theres something funny
what did u remove
when i close the server it doesnt crash anymore
when i try to send a message it throws an exception :d
yes because ur not longer calling serverSocket
right here
ur calling the right socket
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
ah right because u closed the form
no wait
ur not closing the client that would be a server error then
this is in the server
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
maybe ill check first if this object exists
that was meant for the client
before i write or invoke the event
u can check if its Visible
yes!
to answer your question. nothing
actually u can't u needto check if this.Disposing I think
let me try
u removed the try and catch ok
yes
I think its disposing let me check
but it should atleast append text to the TB_Chatbox in my client form
yes because you're not closing the client
yeah im not
so that is fine what I meant is
it should be
having code that updates the ui inside ServerHome_FormClosing makes no sense
because at this point your ui is disposing of it self
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
no ui stuff happening here
i closed the server
no message on the chatbox
now when i close the client:
i think this happens bc my client still tries to communicate with the server
can u scroll up a bit
and somehow the server still receives it's messages lmao
yeah it's still receiving
somehow
remove the try and catch
okay
same exception
open the call stack
then ?
and see where it comes from
line 40 ?
did u hit connect ?
again?
no i just closed the form
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
okay
u shouldn't be getting any messages at this point but I guess you are
how
and since u have a updateui in every single action
how is the server still receiving messages
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
i opened the netstat -an
there are 3 servers running ?
for that to happen
ok?
i closed the server form
so it shouldnt be
even listening
it will stop listening when the serverSocket is Disposed
and how long does that take
as long as it takes to loop thru all the connected clients
+ dispose of it
+ the os to clean up the port
it might take minutes ?
for that I am unsure sorry
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
also
i checked if it's disposing
and it still does this
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.
this.Disposing
wdym by this.disposing
as it would tell us if the form is disposing
oh
this refers to the Form
i thought u meant the textbox
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
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
I assume because some thread was not closed
yes
how do i check which thread is currently running and print it's name ?
can i do that ?
so u need to see which and make the loop stop
can u push and send me the github
okay
I suppose u have no while(true)
nope
and they all have isrunning or something u can turn to false
while(flag)
and while(isReading)
and im setting both to false at formclosing
yeah so maybe some code blocking
so I would need to take a look
GitHub
GitHub - ZoonAttack/ChatApp
Contribute to ZoonAttack/ChatApp development by creating an account on GitHub.
do i need to use some semaphores or smth
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?
yup
btw the disposing check worked?
nope
ok I will try myself in a few
so it all looks good at first glance
try setting up a breakpoint at
Dispose method ?
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
okayu
it would produce a socket exception correct ?
yes when the socket is closed
the serversocket that is
lmao
??
those r my breakpoints
did u set it in the order I said and waited for the first one to hit before setting the others?
no
hold on
let me try again
so on 102
here
when i reach it i put the rest ?
did u set all the bps at this point?
if so then u hit continue
ok i reached it
ill set the breakpoints
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
yeah
i hit continue
and it did nothing
until i closed the client form
no
like u first set the 123
then u close
it will hit that bp
then u set all the other bps
yes
and i hit f11 ?
to continue
then u hit continue
then it will hit the next bp etc, if
do i hit this continue ?
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
dont u mean 102 and 49
yes
ops
when i hit f10
no breakpoint hits
it just gets me here lol
then it should close just fine
should not remain on taskmanager
that is literally the end of the app once it leaves that
it only goes off from the task manager if i close the running solution on vs
the Server process?
weird
yes
it doesnt make sense how it's still listening
even after we closed it
I will take a look here give me a few
maybe its because we didnt shut down the server socket ?
or closed it ?
but it should close when i set the flag to false
look last line
it would not reach Main
if that was the case
if it reaches main it means it has been closed right ?
there is indeed some thread running
š
i guess threads are mischievous
its ok at some point u will learn async
and u will be even more brainfk then now
damn
why should i learn it then š
because sockets use IO and async is much more performant for IO
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
silly
why is this inside the foreach if(serverSocket != null) serverSocket.Dispose();
huh
it shouldnt lmao
and i just noticed im checking twice
if the socket is not null
yeah
look
should i remove the lat if and just leave dispose ?
so yeah this change it properly closes for me
really ?
yeah
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
probably caught in an event issue where calling it in a loop or something makes it hang
yeah probably
okay so this fixed it
does this also fix the updateui thing ?
also u should use .net 8
i dont have .net 8
is it long term support ?
I hope u keep your visual studio up to date at least
no š¤£
i have an update i havent done yet
ill download .net 8
whats the difference ?
why did u suggest that i use it
for one all new versions of dotnet include new features and changes
for 2 .net 6 EOL this year 7 too
shit.
that is something u will eventually have to keep up with
i see
idk what eol is but sure
end of life
it didnt close
can u show me what changed that closed it from task manager ?
why didnt you check if its not nul ?
? does it
oh right
i had this on true instead of NOt true
lmao
so if it was connected it would return
lmao
honestly I would not use that code
why ?
which code u mean
because it can't know when something closed
the socketconnect the poll thing
oh
i see
that's what heartbeat is used for
okay ill use the normal .connected property
lol
new exception
i used exactly that
and i just closed the form
i removed the comment from this
and now this exception happens
unable to read the end of the stream
well im looking so I need a moment
okay
ah well ofc the client doesnt work
huh
wdym
whats wrong with those two
memorystream is empty
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
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
client
all of that bc of not reading properly
yep
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
and on the client closing method also not needed
I suppose its only needed on the loop
so it can tell to stop reading etc
wdym ? how else is it gonna tell teh server that it's disconnecting
yes
if not when the form is closing
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
alright good to know
u are did u read the code?
you said its not needed
so i was just asking why is it not needed
I also had no issues with non-accessible ui I changed it to
read the code first, it is sending the message to the server
ohh alright
the shutdown is only need in the loop
why ?
read evrerything I said slowly looking at the code
I've also explained it above
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
in the server
that's why I said read slowly
I will be back in 20 minutes
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 ?
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
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
i think it makes more sense for the client to close it's own socket
and the server to dispose the resources
yeah
yeah
u would dispose on the client too when u close the app
but for things like reconnect etc u can reuse it
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 ?
Close internally calls Dispose
i see
so the reason I just use Close is because I am aware of that perhaps
so it can be confusing
i see
okayy
thank you
so for the client
if u want to reuse the socket
for reconnecting and stuff ?
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
here ?
look at the link I posted
is that on the server?
yes
no
ohh
i see i see
thank you for the note
the server is fine the way u did there
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 ?
that frigging binaryreader
even I didnt look at it at first
lmao
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
okay ill keep that in mind
youre right its better to keep it in a separate clas
that would however require more work, u would have to create and event for the winform to use to update itself etc
yeah im not that familiar with that yet
events
they confuse me
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
im glad
thank you
and working with sockets with a custom protocol is not exactly simple
all of this time we havent even got to the root of this help thread š
the clients list
specially when u have to deal with errors that sometimes u can't control
i hope it works now
yeahh
lots of exceptions
what root?
like the main issue i created this help thread for
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 š
hmm
what is it
i think youve said it before
let me go back and see
when the message is split into multiple packets
u know the size of it, but you're only reading the first part of it
why would it be split into multiple packets
is it bc its too big ?
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
that logic would happen here on both server and client
but you dont have to worry about that for now...
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()
im closing it here so i think it's fine
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 /
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?
yeah it was throwing an exception
okay ill try that
try returning the shutdown but with dispose instead
because u dont get a Disconnect message on the client
so try{clientSocket.dispose()} finally{clientSocket.close()} ?
when ur closing the client
well this is supposed to be sent to other clients
not me
no shutdown
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 ?
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
yes
no
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
ok then yes let's try to add it back
On the FormCLosing of the client
and see if that works
alright
and i remove it
from the .disconnect ?
can u show me the code?
its on github
yeah I dont have the link
GitHub
GitHub - ZoonAttack/ChatApp
Contribute to ZoonAttack/ChatApp development by creating an account on GitHub.
i just pushed my newest code
so can u check again
should be just
ok let me refresh wait
this is client code
i see
disconnect(true) to reuse the socket later ?
where does the program store the socket ?
line 8?
its not the same socket
as in the same connection
i see
its just the socket data object eetc
anyway
even if u do
U want the isReading = false before that loop
because the thread is not dependent on the socket
ohh right
yeah okay
š
and isreading before even sending the message
should stop THIS client
from reading back
again
I will be back in 20 minutes I just got home so ima eat my food
okay enjoy your food
yeah give these changes a try and lets figure out
;p
but theres something
i dont want it to put that big ass empty space
between messages
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
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()
okay let me tr
can you explain this exception for me
>_> + try and catch
it happens when i close the server form
the only try i have is :
then where is that popup coming from
idk š
that is a MessageBox.Show of a exception
i literally have no try catch
other than that
can u push the code
and what were u doing whe nthat happened I will try to reproduce
done
start the server
connect a client
close the server after the client connects
press the x on the server form
ah ok found it
yep
U dont wnt this
this is a ignore try and catch
i didnt even
see the catch
š
i should do that ?
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
oh
i see
didnt know that
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.
thank you
ObjectDisposedException
ahaa
so it happens after its disposed
might be wiser to do
hmm alright
yeah because its like a internal loop
i see i see
okay so
I never really checked how it works internally
let me get started with the clients list thing
well at least it wasn't a bad exception š
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 ?
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
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 ?
u dont need to make it readonly
isnt an id supposed to be some secret stuff
public Guid Id { get; }
or no
this is pretty much the same as readonly in terms it can only be changed by the constructor
i didnt even know
guid exists in c#
lmao
is it like an integer or a string ?
its a string kind of
alright bet
ill add the logic now
ill need to create
some random
u can use an int if u prefer
16 bit generator
for the id
i think short would fit it fine
for now
if ur using Guid u can just do
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
if u want an int then yeah u would need to do some trickery
what does the init; do
i never saw it b4
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++
a map?
maybe dictionary ?
u would make a Class
meant smth like this
You can
is it even a good idea
to do that ?
use the ID as key and username as value
it would be fast to find the id... not sure it worth it for the purpose of holding just the username
i need the username to put it on the textbox
u already have a list with your clients
so
I would just add the username and id to it
i already have that
a list of client objects
yeah I would take advantage of it
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
I mean do the way u find it will work š its your chat
if it doesn't work we see after
okay let me try then
part of learning is solving the problem
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 ?
and is this a good idea ? the new guid(string)
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
you dont need to use | anymore
every string u write to binarywriter
comes with a prefixed size
but im sending both Username and ID
so you can just read it back as string just fine
and then feed it to
new Guid(string)
i see
dont send them together
bw.Write(id)
so i can do two sends ?
bw.Write(username)
will the socket wait ?
no
1 send
just dont write then as 1 string
ohh
okay if i do bw.write(id) and bw.write(username) how would that work ?
this is like 4 byte each
then u can read it back as
var guid = new Guid(br.ReadString());
var username = br.ReadString();
oh
ahaa so readstring reads a fixed amount of bytes ?
no
strings are different
i see
does readstring move the cursor after its done reading ?
rrr
what
lmao
getbytes I was using getstring lol
leowest
REPL Result: Success
Result: string
Compile: 323.711ms | Execution: 20.269ms | React with ā to remove this embed.
so your username to bytes is that
thats hexa
and then binary writer
adds the size in front of it
so 045A6F6F6E
i see
leowest
REPL Result: Success
Result: string
Compile: 337.341ms | Execution: 20.287ms | React with ā to remove this embed.
as you can see the string changes based on the size
yeah its a bit more complicated
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
got it
leowest
REPL Result: Success
Result: string
Compile: 332.366ms | Execution: 20.663ms | React with ā to remove this embed.
ah here is one example
as u can see accent Ć© is 2 bytes for example
interesting interesting
but either way
the binarywriter will take care of it for u
on both sides
since it prefixes the strings with a size
huh ?
oh mb
.tostring
ill just send it as string
leowest
REPL Result: Success
Result: string
Compile: 237.458ms | Execution: 18.056ms | React with ā to remove this embed.
can u read this ?
the guid?
no its just random
i see
this kinda confusing
and seems messy
what?
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
I see, u mean its confusing that u have to have different methods to send and receive now because the updatelist is different
yeah
u can probably get away with it by customizing the clientmessage
i might
maybe adding a Sender property
and keep just 1 broadcast for everything
that holds both
i will try this and see if it works first
this was mine
From and To are ids
i see i see
ill see if it works and then adjust it later
To is not always sent to its string?
i just wanna get it to work
but it seems more efficient to hold the from and to
esp in ids
yes
having mid terms isnt helping š
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
not working š
ANYTHING that reads anything from the br will move it
i see
so if u do br.ReadString() at the id position
then next is the username
okay
and how do u know its not working?
u only assigned it locally in your code
its not working
because
the updatelist in the client code isnt being accessed
i put a messagebox.show in it
and it didnt appear
oh
wait
what is onlineClients
also L
its a dictionary
wait its not working bc i didnt even start it
: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*
yeah ijust realised
look
š¤£
they are both getting different lists
š
i think ill do it a better way
:PatrickChad:
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 š
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
because that is not ObjectDisposed
if u specify something in the catch it will look for that
ahaa
so I guess u do need to remove the () and just ignore all for it
when did that one hppaned do u remember?
what did ?
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
yeah how do i send a whole list object
the exception
ohh
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
so i keep writing it to the binarywriter
u dont broadcast u just use the socket directly of the user that just connecte and send the full list
and when i read it i loop and keep reading it
yes u might want to write the size of the list
and pushing it to the textbox
and the the id /user of each user
im confused
what is the list for ?
list dictionary whatever u are u using that have the id/username
what i decided was im gonna have onlineclients dictionary in the server
and i only send usernames
to every client
bw.Write(list.Length);
loop
bw.Write(id);
bw.Write(user);
end loop
i see
okay let me try
well the full list of users u only send once
when they connect
after that u can just broadcast increments
what if there is a client
then another client connects after
what do i do then
same thing they are connected sequentially not concurrently
what is the lin to your project again?
GitHub
GitHub - ZoonAttack/ChatApp
Contribute to ZoonAttack/ChatApp development by creating an account on GitHub.
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
how do i update the list ?
u mean i just broadcast the new user's id and username ?
or what
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
this ?
i see
okay i got it
let me try
whats that
idk nvm
i was trying smth lmao
so right after the user connects
i send him the full list
yes
using their socket
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
sure
since i have the message size
but ideally u should add the list size
brb food here
alr eat well
alright
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
im gonna do it like this
or I suppose u could check if u reach the end of the strema
since im sending the count of elements at first
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
do i need if statements
so u wouldn't need 2 separted updates
or it will handle it on its own
dont think so no
I will be back in 30 minutes gona eat my food
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
well that would not work
i adjusted it
ok that is more like it yes
i have a question
u dont use bitconverter there
does bitconverter
yeah i figured
u use br.ReadInt32();
it doesnt move the stream
lmfao
yeah
i was just about to ask š
we only use it for the first 4 bytes because they are special
i see
i alrdy read the first 4 bytes to know the size of the whole message
then i read the number of clients
but yes that should work
and move the stream to the beginning of the list
let me see
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
:yesowo:
Also keep in mind that list does not include the server
well i found a bug
unless u add a fake client to the list as the server
i dont think mine does
now enter with more users
this is the broadcast method im using
this ME bug
is so annoying š
its throwing me off
but it's working
what is the bug?
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
u would have to modify here
if username == me, add me
let me try
so it only changes client side
not working
what u wrote
push it so I cna check
its pushed
well yeah ofc it wont work
ur not matching message with the actual username lol
huh
i dont get it
message == TB_Username.Text?
its supposed to send ME
oh
wait but i mean
your username is oh
here
u want it to be me
if(client == sender)
send "me"
so the username shouldnt even be there
I mean u dont need to handle that server side
u can handle that client side
but sure
i think its bcz of this
hace u checked if client matched name
` //Tell other clients a user has just joined!
Broadcast(client, client.Name, ActionType.USERCONNECTED);
if (client == sender)
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
well now its working differently š
yeah
ah i see
welll if u dont make Client IEquatable
then sernder wont know how to match client
what does that mean
ohh
its an interface that makes a contract with your class to implement 2 comparison methods
yeah i see
so that it knows how to compare an object of the same type
okay ill just make it compare names
u can do that too
what is the function that
gets the top element of the list ?
list or dictionary?
could be as simple as list[0]
list
no i meant the last element
imagine if u could swap that 0 for the count of the list
lmfao
soo i know the fix for the (me) thing now but
why does this not wor k?
can u check my code now ?
check what hte broadcast of list?
okay i get the problem i think
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
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
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)
so the problem is SendToAllExcept
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
yep same thing
lol i already had the sender socket as a parameter
but never used it
š
wait
nevermind
im blind i think i need sleep
:awesome:
why
is this because
count is bigger since i skipped 1 client ?
ill subtract 1 from count and see
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
yes
so the count should be right?
idk i subtracted 1 and it worked
I guess breakpoint there
and go 1 by 1
but now the (me) doesnt appear in the clients list
try using Length instead of Count
that does not exist
it should
it doesnt
what is clients?
List<Clients>
maybe im drunk let me try
weird ok
leowest
REPL Result: Success
Console Output
Compile: 481.101ms | Execution: 41.888ms | React with ā to remove this embed.
looks fine it shouldn't read beyond the stream
ahhh
weird
okay it's working
after i deducted 1 from count
what was causing this is
this commented line
i was skipping it
so it was sending nothing
well if u -1 it will be missing 1 client
yes
which is the sender client
br.Write(clients.Count) says count is int?
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 š
this adds (me) as a username to the list in the client code
yeah but that is nasty
in terms of missing one
i know
well i guess i can just
manage it in client code better
can u push the project with the latest I will take a look in a few
instead of ignoring 1
do u think managing it in client code better ?
okay im gonna sleep anyway got another exam tomorrow
I think changing the me client side is the best option here
I dont see why that would be a server job anyway
yeah fair enough lmao
okay its uploaded
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
Weird lol
I do get the extra me thou from the connected action thou
so I guess u could just do this instead?
also this
remove the -1 and the condition inside
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
just missed that one thing
when the packet is too big
then I would say its pretty decent
:catlaugh:
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.
read from there to the image
I wont help on this one š
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 ?
how to access and record the mic?
encoding
that entails a lot of things
how do i make a voice call
basically
what should i learn
to be able to do that
well part of i u already learned with the custom packet socket
the principle is the same except u would be sending pcm data
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"
what u have right now could easilly add audio
but real time is more complicated than just that
do you mean
voice notes ?
like whatsapp ?
or discord
voice notes?
voice messages
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
woahh
with a small delay
alright interestingg
ill probably need a button that starts recording from a mic and sends packets then
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.
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
ill try to get the packets thing down first then
the answer to the packets things is very simple, but I believe u should be able to solve that problem yourself
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 ?
just run your client
write a big message like
does it have to do with the socket.sendbuffersize ?
BlazeBin - kwknekhlviam
A tool for sharing your source code with the world!
what is this
ohh
the big message lmfao
okay
it sent just fine
lol
i sent all of this
i think i just havent reached that yet
i printed the buffer.length
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 ?
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
what's the difference ?
$tias
yeah how do i check the bytesRecevied of the actual data lmao
doesnt the actual data get sent to bytesRead ?
returns
okay i checkd that
it was like 3k
it didnt split
or do anything
on the bytesreceived?
not the size
yup
its not the first 1 its the 2nd receive
yes
i checked the second
then send a bigger message I guess your MTU might be 4096
or bigger
lmao
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
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 ?
well u would get an error
oh I see what might be happening
can u link me ur project?
okay
u have a default in your switch?
no
GitHub
GitHub - ZoonAttack/ChatApp
Contribute to ZoonAttack/ChatApp development by creating an account on GitHub.
ill go eat right now
add a
and see on the output of vs if it says something
lol
what the hell
MY BAD LOL
i commented the bytesRead
but umm
why is my buffer size this
lol
i only pressed connect btw
:kekw:
well yeah u commented the 2nd Receive
ofc it will fail
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
8192
so yeah needs to be a message bigger than 8.2k so it splits
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
u dont need to set it
just send a buffer bigger than 8.2k
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
i think it split yeah
if u have the throw on the server hwen it splits it will throw
what throw ?
the if after the 2nd receive
i do have it
it didnt throw
well yeah u dont have it
i do
put it back in and when it throws check the bytesread and the size
the second if
yes if it splits it will tell u
are u sure the size of this message should make it split ?
think so its bigger than 8.2k
it didnt š
did u change the buffer size?
no right?
no i didnt
i didnt change the receivebuffer size
I guess its different in your system then its on mine then
this is the bytesRead
then increase it
copy paste twice
it says the default for me is 8k too btw
until it throws and u know what size is your buffer
idk how it's different if the default is the same
i sent this
no exception was thrown
lmfao
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
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 ?
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.
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
isnt it the same app ?
or does the mtu have to do with your own isp ?
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
here
i think this shows something
but i cant read it lmao
can u read it
they are both 1500
but perhaps some other config might have changed how it handles it
oh
anyway go do the voice thing u want
is it not the bytes in and bytes out ?
I will research on that later
those are total bytes in and out from the time u turned your network on
until now
does that mean your mtu limit is 7k ?
that was the one I was using so I guess
then why did it crash on 7k ?
ĀÆ\_(ć)_/ĀÆ
all I know is that it can and will split the packet
okay i have a question
what the exact terms are for it to happen I dont know
is the textbox limit for characters 32k ?
ive put 70k characters in it and it only kept
this
default is 32767
so i guess i cant even try out smth bigger than 32k lmao
Think u can increase MaxLength
what can i make it as ?
so
textbox.MaxLength = int.MaxValue;
ohh okay
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
holy shit
š
it didnt split
maybe its something to do with localhost
try binding to your external ip
192.168.1.1?
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
and external ips
is this the external ?
internal
well idk my external ip
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
well
thats good to keep in mind but im kinda glad that no splitting is happening
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.
what's weird though is ive tried this before
on a console application
it will tell u your external ip
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
very likely your provider modem is in NAT
it's not splitting
so u only get internal ips
i think i remember having nat closed
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
no i have router > pc
my router is tp link
do you know that brand ?
sure if ur router is where your provider connects to and its directly connected to your pc
and its set to bridge mode
idk if it's bridge mode or not
but yeah
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
i see
i think it's stuck
try this one https://nordvpn.com/pt-br/what-is-my-ip/
not even opening
š
http://checkip.dyndns.org/
how does nordvpn not open for u
lol do u live in china
something similar š
there u go
that is your current external ip
delete it š
can people hack me through my external ip ?
not my internal ?
yes it needs the external
and a point of vulnerability
i see
like it tells me your from somewhere in Italy for example
let me try my external ip
i see
lol
well u wont be able to bind ot your external ip
since you're behind a nat
i see
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
too much work
yk what ill just handle the packet splitting
without experiencing it
maybe ill experience it on you š
giza
well u could set it to 1024 on send/receive and see if that works
before u Bind
yeah yk what ill do that
and try to figure out the packet handling thingy
here
ill now try
š
maybe u need to set it on the actual client socket u receive that is also worth checking
ohh ok
so yeah, just setting on the server under Bind
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.
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
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
did u try the changes above and it does not break?
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
gl
thank you bro
youve helped me alot ive learnt so much from you. thank you
its the rare case of iwmm
what is iwmm
š
yeah it works on my machine š
so basically scrapping
yeah scrapping
kind off tables then can't discuss it here
yeah but i have smth to say ab packet thingy
its one of those grey areas of subject
what is it against the law or smth
lol
scrapping yeah
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
$scrape2
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.
ill check it out
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
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
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
isnt the bytesRead all the bytes i got from the send method ?
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
i see
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
how do i check if the queue is empty
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
yeah thats why i need to check if the buffer still has available space
so if the bytesRead is still less than the buffer size
and for this scenario u would use that
the offset will be bytesRead right ?
or buffer.length i mean
the offset is where it will start writing
yes
so the first receive it starts at 0
then it should start at buffer.length
the 2nd will be 0+bytes writen from last receive
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
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
leowest
REPL Result: Success
Console Output
More...
Compile: 432.247ms | Execution: 92.022ms | React with ā to remove this embed.
so as u can see when u initialize your buffer with size its a bunch of 0's
i see
once u copy part of the buffer
it changes into something
so why does splitting happen then ? if my bytes array is always [size] which is the size of the message ?
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
ahhh
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?
is the other packet still sent ?
ohh
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
will the other packet be sent after i receive the first 500 in the buffer ?
yes
not before
not in between
just after
right ?
it will either be instantly behind it
or slightly behind
how do i check that lmao
yes its sequential
if nothing is behind the packet i got then bytesRead will be 0 right ?
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
is bytesRead is not equal to size ?
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
yeah so i should check if the bytesRead is smaller than buffer size which is [size]
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
does buffer.length give me the length of the data inside it
or even the 0s ?
no
buffer.Length is always size
so the size of the whole message
not whtt i received
leowest
REPL Result: Success
Console Output
Compile: 479.779ms | Execution: 49.100ms | React with ā to remove this embed.
i see
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
is this logical enough
lol
tyt
well it wouldn't update dataRemaining as is
also u can't use bytesRead as offset
offset is incremental
wdym incremental
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?
yes so i need to keep track of the bytesRead
yes
like this ?
where u have dataRemaining its just size
in the Receive after the offset
oh right
so dataremaining is supposed to be size - bytesRead though
right ?
offset needs to increment after u receive not before
okay
flags None
yes but the way u have it, it wont update either
because its outside the loop
ohh mb mb
ill set it to socketflags.none
how
this is supposed to update it
this is inside the loop
I missed thathehe its right
is this code supposed to plug everything until it matches the size
into the buffer ?
u know u can just make
and inside
well fair enough
buffer, offset, dataRemaining, Flags none
same with dataRemaining needs to run after the Receive
nothing happens before it
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
that is what the loop is doing
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
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?
here is my whole code until the loop
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 ?
oh
i get it now
u still missing 1 piece
look at my curved arrow
rightt
so now this makes more sense
fair enough
And this is how I did it as a extension
this makes more sense
its essentially the same thing
but prettified
and in the common library
so when do you call that receiveall ?
and then u would use it like
wait
how did u connect it to the socket
so u could use it under the socket class
(this Socket socket,
its a helper method that extends the socket
ohh right right
well ill keep it like that for now š
let me try it
ive set the send/receive buffer size to 1024
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
okay tyt
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 ?
did u do e.Handled = true?
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 ?
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
Wdym
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
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
fair I really wonder what you might have that causes it to not respect the configurations of the socket
maybe some screwed windows settings lmao