在本文中,将探讨如何使用C#和Universal Windows Platform (UWP) 在Raspberry Pi2(作为服务器)和Windows 10 PC(作为客户端)之间建立TCP/IP网络通信。这种通信方式允许PC向Raspberry Pi发送消息。
UWP - Universal Windows Platform Universal Windows Platform 是微软推出的一种新型项目类型,它允许应用程序在任何Windows平台(如Windows 8或更高版本、Xbox、Windows Phone等)上运行,而无需任何修改。现在,拥有了一个“Manifest”,如果不在manifest中授予权限,应用程序将无法工作。有关更多信息,请访问以下链接:
Windows 10 IoT Core Windows 10 IoT Core 是Windows 10的一个版本,它针对有或没有显示屏的小型设备进行了优化。在本文撰写时,Windows 10 IoT Core支持以下设备:
在这个项目中,创建了一个包含两个项目的“解决方案”,一个使用UWP(客户端),另一个使用Background IoT(服务器)。要访问整个项目,请访问以下链接:
在服务器端,将展示如何绑定某个端口并等待连接。为此,创建了一个名为SocketServer的类。
private readonly int _port;
public int Port {
get {
return _port;
}
}
private StreamSocketListener listener;
public delegate void DataRecived(string data);
public event DataRecived OnDataRecived;
public delegate void Error(string message);
public event Error OnError;
public async void Star() {
listener = new StreamSocketListener();
listener.ConnectionReceived += Listener_ConnectionReceived;
await listener.BindServiceNameAsync(Port.ToString());
}
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) {
var reader = new DataReader(args.Socket.InputStream);
try {
while (true) {
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
return;
uint stringLenght = reader.ReadUInt32();
uint actualStringLength = await reader.LoadAsync(stringLenght);
if (stringLenght != actualStringLength)
return;
if (OnDataRecived != null)
OnDataRecived(reader.ReadString(actualStringLength));
}
} catch (Exception ex) {
if (OnError != null)
OnError(ex.Message);
}
}
public void Run(IBackgroundTaskInstance taskInstance) {
...
taskInstance.GetDeferral();
var socket = new SocketServer(9000);
ThreadPool.RunAsync(x => {
socket.Star();
socket.OnError += socket_OnError;
socket.OnDataRecived += Socket_OnDataRecived;
});
}
不要忘记给予应用程序客户端和服务器的能力,如下图所示:
客户端已在Windows 10上进行了测试,使用UWP。要发送字符串,创建了一个名为SocketClient的类:
private readonly string _ip;
private readonly int _port;
private StreamSocket _socket;
private DataWriter _writer;
private DataReader _reader;
public delegate void Error(string message);
public event Error OnError;
public delegate void DataRecived(string data);
public event DataRecived OnDataRecived;
public string Ip {
get {
return _ip;
}
}
public int Port {
get {
return _port;
}
}
public async void Connect() {
try {
var hostName = new HostName(Ip);
_socket = new StreamSocket();
await _socket.ConnectAsync(hostName, Port.ToString());
_writer = new DataWriter(_socket.OutputStream);
Read();
} catch (Exception ex) {
...
}
}
public async void Send(string message) {
_writer.WriteUInt32(_writer.MeasureString(message));
_writer.WriteString(message);
try {
await _writer.StoreAsync();
await _writer.FlushAsync();
} catch (Exception ex) {
...
}
}
要读取内容,代码与类ServerSocket中使用的代码相同。
public void Close() {
_writer.DetachStream();
_writer.Dispose();
_reader.DetachStream();
_reader.Dispose();
_socket.Dispose();
}