net.SendToServer doesn't do anything

Hello everybody! As I am still working with networking, I came across a problem with net.SendToServer, in a certain case, it doesn’t do anything. Let me give an exemple

Here is my client side file


net.Start('SendToServer')
   net.WriteString('Test string.')
net.SendToServer()

Then I have my server side file:


util.AddNetworkString('SendToServer')

net.Receive('SendToServer', function()
   local str = net.ReadString();
   print('Received the string ' .. str) -- Should print the string, but nothing happens.
end)

In this case, nothing happens, and I checked, my client side file is included without any problems.
But, if I put my net message in a console command and then run it, it works.

Example:


concommand.Add('cl_sendnetmsg', function()
   net.Start('SendToServer')
      net.WriteString('Test string.')
   net.SendToServer() -- This time, it sends it to the server.
end)

In this case, if I run my console command “cl_sendnetmsg”, it works, and the networked string is printed server side.

Maybe the net.SendToServer is sent before the client can send net messages to the server. I know that a timer would fix it, but it wouldn’t be a good way of fixing it. I just would like to know why the message isn’t sent to the server and the bets “moment” (hook?) to send the message to my server. Thank you in advance!

Change your client to this:
[lua]
hook.Add(“InitPostEntity”, “PlayerLoadedHook”, function()
net.Start(‘SendToServer’)
net.WriteString(‘Test string.’)
net.SendToServer()
end)
[/lua]

The reason why it fails is because it’s getting called as soon as the file loads, not when the client is in a ready state to send net messages.
You usually wouldn’t run it like that, so this wouldn’t be an issue.

Well, thank you a lot for the quick reply! But if it is just a matter of "being called as soon as the file loads, would the hook “Initialize” work better? I’m pretty sure it’s executed before the “InitPostEntity” hook, but still, maybe it would send the message too soon?

Thank you again for your reply!

Some tests revealed that the Initialize hook is also too early, and that InitPostEntity truly is the earliest called hook that allows to send net messages to the server. Thank you a lot for your help!