多次序列化到套接字需要大量的ram内存。

时间:2019-03-21 11:13:45

标签: c# sockets

因此,只要麦克风有数据,它将发送到服务器。 而且会占用大量内存,每2秒大约2MB。 而且那不会停止。 我必须以其他方式编写还是没有其他方式? Connections是包含该方法的静态类。

[Serializable]
public class Communication
{
    public enum ComType
    {
        Recording,
        Sound
    };
    public ComType comType;
    public object data;
}

microphone.DataAvailable += (s, args) => 
        {
            if (!micMuted)
            {
                try
                {
                    communication.data = args.Buffer;//Instance of communication class
                    Connection.SendToServer(communication);//The line that boosts the memory usage
                }
                catch
                {

                }
            }
        };

public static class Connection
{
    public static Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
    public static BinaryFormatter formatter = new BinaryFormatter();
    public static NetworkStream stream;
    public static void Connect(string ip, int port)
    {
        try
        {
            socket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
            stream = new NetworkStream(socket);
        }
        catch
        {
            System.Windows.Forms.MessageBox.Show("Could not connect to servers please restart program.\nYou might be offline");
        }
    }

    public static void SendToServer(object obj)
    {
        try
        {
            formatter.Serialize(stream, obj);
            stream.Flush();
        }
        catch
        {
        }
    }
}

0 个答案:

没有答案