gpt4 book ai didi

c# - 如何序列化媒体对象(音频和图片)以进行套接字传输?

转载 作者:行者123 更新时间:2023-12-03 12:01:27 25 4
gpt4 key购买 nike

我希望我的应用程序能够通过套接字与PC客户端通信。
我已经知道如何对字符串执行此操作。

我的问题是,我希望能够发送音频文件和图片,如何将iamge/音频文件转换为字符串/位流并发送呢?

这是我的套接字类(class):

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

关于c# - 如何序列化媒体对象(音频和图片)以进行套接字传输?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8137351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com