我希望我的应用能够通过套接字与PC客户端通信。 我已经知道如何为字符串做到这一点。
我的问题是,我希望能够发送音频文件和图片,如何将iamge / audio文件转换为字符串/位流并发送?
这是我的套接字类:
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();
}
}
我想修改它以便能够发送图片和音频文件。
答案 0 :(得分:2)
您当前的Send方法使用字符串属性作为数据。您可以使用包含数据的字节数组或流来重建它。
您可以使用此示例查看如何从图像进行流式传输和返回,尽管这不使用套接字而是使用本地存储。关于如何做到这一点的原则保持不变: http://blogs.microsoft.co.il/blogs/tomershamam/archive/2010/10/12/saving-and-loading-captured-image-to-and-from-wp7-isolated-storage.aspx