markiodev / Networker

A simple to use TCP and UDP networking library for .NET. Compatible with Unity.
MIT License
477 stars 77 forks source link

Server Send does not work #48

Open mahmah2 opened 5 years ago

mahmah2 commented 5 years ago

Hi,

I have got stuck in a weird situation. I want to initiate a send from the server side to all of the clients. So logically this should work:

                private IServer _server
                 ...
                var connections = _server.GetConnections().GetConnections();

                foreach (ITcpConnection connection in connections)
                {
                    connection.Socket.Send(Encoding.ASCII.GetBytes("COMMAND1"));
                }

But client doesn't receive this command.

Now if I save the server context somewhere and reuse it later it works:

private ISender _sender;

ServerPacketHandler_OnProcess(object sender, string e)
{
            _sender = (sender as IPacketContext).Sender;
}

Now this one will work :

                _sender.Send<string>("COMMAND1");`

What is the correct way of initiating a send from the server. Its not in the example and tests either.

erictuvesson commented 5 years ago

When you use Socket.Send you don't add the packet header and just send it as a raw string. So the client doesn't know what to do with it so it just ignores it.

I am not sure if this is on the master branch

When calling TcpSender.Send<T>(..) the packet is serialised with a header. https://github.com/MarkioE/Networker/blob/feature/3.0/Networker/Common/TcpSender.cs#L21

sbaum23 commented 4 years ago

@mahmah2 I was running into the same issue with the client not receiving my packets when using Socket.SendAsync. I was able to get it working using PacketSerialiserProvider.PacketSerialiser.Serialise<T>

Assuming the packet type I'm trying to send was:

public class MyAwesomePacket
{
   public int Id { get; set; }
}

Then using the Socket worked:

var socket = .... // code to get the Socket of the client you are wanting to send to.
var packet = new MyAwesomePacket { Id = 1 };
socket.SendAsync(PacketSerialiserProvider.PacketSerialiser.Serialise<MyAwesomePacket>(packet), SocketFlags.None);

For serialization I was using MessagePack.