我如何序列化媒体对象(音频和图片)用于套接字传输

本文关键字:用于 传输 套接字 音频 序列化 媒体 对象 | 更新日期: 2023-09-27 18:14:34

我希望我的应用程序能够通过套接字与pc客户端交谈。我已经知道如何处理字符串了

我的问题在这里,我希望能够发送音频文件和图片,我如何将图像/音频文件转换为字符串/比特流并发送它?

这是我的套接字类:

public class SocketClient
{
    Socket socket = null;
    static ManualResetEvent clientDone = new ManualResetEvent(false);
    const int TIMEOUT_MILLISECONDS = 5000;
    const int MAX_BUFFER_SIZE = 2048;
    public SocketClient()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    }
    public string Send(string serverName, int portNumber, string data)
    {
        string response = "Timeout";
        if (socket != null)
        {
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.RemoteEndPoint = new DnsEndPoint(serverName, portNumber);
            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                response = e.SocketError.ToString();
                clientDone.Set();
            });
            byte[] payload = Encoding.UTF8.GetBytes(data);
            socketEventArg.SetBuffer(payload, 0, payload.Length);
            clientDone.Reset();
            socket.SendToAsync(socketEventArg);
            clientDone.WaitOne(TIMEOUT_MILLISECONDS);
        }
        else
        {
            response = "not initialized";
        }
        return response;
    }
    public string Recieve(int portNumber)
    {
        string response = "Timeout";
        if (socket != null)
        {
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                if (e.SocketError == SocketError.Success)
                {
                    response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
                    response.Trim(''0');
                }
                else
                {
                    response = e.SocketError.ToString();
                }
                clientDone.Set();
            });
            socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, portNumber);
            clientDone.Reset();
            socket.ReceiveFromAsync(socketEventArg);
            clientDone.WaitOne(TIMEOUT_MILLISECONDS);
        }
        return response;
    }
    public void Close()
    {
        socket.Close();
    }
}

我想修改它,使其能够发送图片和音频文件

我如何序列化媒体对象(音频和图片)用于套接字传输

当前的Send方法使用字符串属性表示数据。您可以使用包含该数据的字节数组或流重新构建此文件。

您可以使用这个例子来了解如何从图像到流并返回,尽管它不使用套接字,而是使用本地存储。关于如何做到这一点的原则保持不变:http://blogs.microsoft.co.il/blogs/tomershamam/archive/2010/10/12/saving-and-loading-captured-image-to-and-from-wp7-isolated-storage.aspx