从长度未知的套接字接收数据
本文关键字:数据 套接字 未知 | 更新日期: 2023-09-27 18:08:29
我正在使用新的Windows Universal应用程序架构与Windows 10建立客户端-服务器网络。目的是要有一个设备充当服务器,其他设备可以连接并向服务器发送数据。我的目标是通过LAN做到这一点,至少现在是这样。让我们看一些代码:
我提出的结构是几个类,Server
和Client
。一个有多个客户端的服务器将监听来自客户端的数据,这里是Client
。
注意:我将提供完整的代码,以便于你们调试。
public class Client
{
public StreamSocket Socket { get; internal set; }
public bool IsConnected { get; internal set; }
public async Task ConnectAsync(string ip, string port = "80")
{
try
{
//Create a socket and connect to the IP address.
Socket = new StreamSocket();
await Socket.ConnectAsync(new HostName(ip), port);
IsConnected = true;
}
catch (Exception)
{
IsConnected = false;
throw;
}
}
public async void SendDataAsync(string data)
{
//If we're not connected, then bugger this.
if (!IsConnected)
throw new InvalidOperationException("The client is not connected to the server, connect first, then try again.");
//Send the data.
DataWriter stream = new DataWriter(Socket.OutputStream);
//Write and commit the data to the server.
stream.WriteString(data);
await stream.StoreAsync();
}
public void Disconnect()
{
if (IsConnected)
{
//TODO: Disconnect safely (Still working this one out)
//Dispose of the socket.
Socket.Dispose();
Socket = null;
}
}
}
我们感兴趣的位是SendDataAsync
方法,这是我们向服务器发送数据的地方。这是Server
.
public class Server
{
public List<Client> Clients { get; private set; } = new List<Client>();
public StreamSocketListener Listener { get; private set; }
public string Port { get; private set; }
/// <summary>
/// Gets the local IP address of the device.
/// </summary>
public HostName HostName
{
get
{
return NetworkInformation.GetHostNames()
.FirstOrDefault(x => x.IPInformation != null
&& x.Type == HostNameType.Ipv4);
}
}
public Server()
: this("80")
{ }
public Server(string port)
{
if (string.IsNullOrEmpty(port))
throw new ArgumentNullException("port");
Port = port;
}
public async Task Setup()
{
Listener = new StreamSocketListener();
//Open a port to listen for connections
await Listener.BindServiceNameAsync(Port, SocketProtectionLevel.PlainSocket);
Listener.ConnectionReceived += Listener_ConnectionReceived;
}
private void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
Client client = new Client()
{
Socket = args.Socket
};
//Add the client to the collection.
Clients.Add(client);
//Wait for some data.
WaitForMessage(client);
}
private async void WaitForMessage(Client client)
{
//Open up a stream
DataReader stream = new DataReader(client.Socket.InputStream);
//Wait for 12 bytes (wtf, what if I don't know for sure how much data is arriving?)
await stream.LoadAsync(12);
//Get the message that was sent.
string message = stream.ReadString(12);
}
}
我们感兴趣的是WaitForMessage
方法,这是我们等待客户端发送一些数据给我们的地方,然后我们将用它做一些有用的事情。
MainPage.xaml.cs
代码:
public sealed partial class MainPage : Page
{
private Server _Server;
private Client _Client;
public MainPage()
{
this.InitializeComponent();
SetupServer();
ConnectToServer();
}
private async void SetupServer()
{
//Create the server
_Server = new Server();
await _Server.Setup();
}
private async void ConnectToServer()
{
//Create a client and connect to the server.
_Client = new Client();
//Note, this may not be your IP address, input your local IP instead (ipconfig in command prompt)
await _Client.ConnectAsync("192.168.1.5");
//Send some data to the server.
_Client.SendDataAsync("Hello World!");
}
}
那么,回到实际问题上来。下面的代码给我带来了麻烦:
//Wait for 12 bytes (wtf, what if I don't know for sure how much data is arriving?)
await stream.LoadAsync(12);
//Get the message that was sent.
string message = stream.ReadString(12);
这里的问题是,它可能并不总是12字节被发送到服务器。现在是12因为这就是"Hello World!"的大小字符串,否则,如果缓冲区较长(大于12),它将永远不会完成接收数据,因为它期望更大的字节数。
就像我提到的,我对网络很陌生,但这真的没有任何意义,这是我所期望的:
- 客户端连接到服务器。 客户端发送一些数据,然后关闭流。
- 服务器识别到数据流已经关闭(可能是一个事件或其他),并相应地采取行动。
不要等待给定的字节数。
也许我看这个问题完全错了,我应该采取不同的方法吗?
这是我一直在考虑的一个主意:
- 客户端告诉服务器它将发送多少字节。
- 服务器设置流并等待这些字节。
- 客户端发送字节。
- …
- 利润!
然而,事实是,由于我对这些东西完全不熟悉,是否存在一个最佳实践方法来实现客户机-服务器架构?
使用说明:
DataReader reader = new DataReader(...);
reader.InputStreamOptions = InputStreamOptions.Partial;
uint bytesLoaded = await reader.LoadAsync(12);
然后,LoadAsync()将加载1到12字节之间的内容。如果它加载零字节,则可以假设流结束。
还有其他的InputStreamOptions,有时你可以混合它们。