我尝试在UWP-programm和“普通”C#应用程序之间建立连接。
UWP:
StreamSocket s = new StreamSocket();
await socket.ConnectAsync(new HostName("localhost"), "8003");
BinaryWriter bw = new BinaryWriter(socket.OutputStream.AsStreamForWrite());
String toSend = "Hello World!";
byte[] text = Encoding.UTF8.GetBytes(toSend);
byte[] number = BitConverter.getBytes(text.Length);
if(BitConverter.isLittleEndian) Array.Reverse(number);
bw.Write(number, 0, number.Length);
bw.Write(text, 0, text.Length);
“正常”C#,在TcpListener建立新的ClientThread之后:
//client was accepted by the server and is an instance of TcpClient
BinaryReader br = new BinaryReader(client.GetStream());
byte[] number = new byte[4];
br.Read(number, 0, number.Length);
if(BitConverter.isLittleEndian) Array.Reverse(number);
int size = BitConverter.ToInt32(number);
byte[] buffer = new byte[size];
br.Read(buffer, 0, buffer.Length);
String recieved = Encoding.UTF8.GetString(buffer);
Debug.WriteLine(recieved);
但服务器没有收到任何东西。并且int大小为0.但是如果我在“普通”C#应用程序上运行UWP代码,通过用client.GetStream()替换s.OutputStream.AsStreamForWrite()并使用TcpClient而不是StreamSocket,服务器接收文本。我做错了什么?
Greets Marcel