Я использовал этот образец от Microsoft здесь https://msdn.microsoft.com/en-us/windows/uwp/networking/sockets для отправки данных от одного к другому, и это сработало. Как я могу отправить байт [] или поток (скажем, изображение или видео) с помощью сокетов?Как отправить файл байта [] с использованием сокетов в проекте UWP?
Сервер:
private async void btnConnect_Click(object sender, RoutedEventArgs e)
{
try
{
StreamSocketListener socketListener = new StreamSocketListener();
socketListener.ConnectionReceived += SocketListener_ConnectionReceived;
Windows.Networking.HostName host = new Windows.Networking.HostName("192.168.1.4");
await socketListener.BindEndpointAsync(host, 8887.ToString());
}
catch (Exception ex)
{
//Handle exception.
}
}
private async void SocketListener_ConnectionReceived(StreamSocketListener sender,
StreamSocketListenerConnectionReceivedEventArgs args)
{
Stream inStream = args.Socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(inStream);
string request = await reader.ReadLineAsync();
Stream outStream = args.Socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(outStream);
await writer.WriteLineAsync(request);
await writer.FlushAsync();
}
Клиент:
private async void btnSend_Click(object sender, RoutedEventArgs e)
{
try
{
Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();
Windows.Networking.HostName serverHost = new Windows.Networking.HostName("192.168.1.4");
string serverPort = "8887";
await socket.ConnectAsync(serverHost, serverPort);
Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
string request = "test";
await writer.WriteLineAsync(request);
await writer.FlushAsync();
//Read data from the echo server.
Stream streamIn = socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(streamIn);
string response = await reader.ReadLineAsync();
}
catch (Exception ex)
{
//Handle exception here.
}
}