var tcpClient = new TcpClient(); if (!tcpClient.ConnectAsync(ip, 8787).Wait(2000)) { thrownew Exception($"{userName}不想讓人知道他在幹麻"); } var stream = tcpClient.GetStream();
查詢命令接收端
接收命令當然也如上面使用Tcp。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var listener = new TcpListener(IPAddress.Any, 8787); listener.Start(); var recData = newbyte[1024]; while (true) { try { if (listener.Pending()) { Console.WriteLine($"有人想知道你在幹麻 - {DateTime.Now}"); } } catch (Exception ex) { } }
接收端回傳螢幕截圖
要如何簡單有效的知道對方在幹麻呢?或許直接回傳螢幕截圖可以達到目的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var bounds = Screen.GetBounds(Point.Empty); using (var bitmap = new Bitmap(bounds.Width, bounds.Height)) { using (var g = Graphics.FromImage(bitmap)) { g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size); } bitmap.Save(memoryStream, ImageFormat.Jpeg); } var client = listener.AcceptTcpClient(); var fileBytes = memoryStream.ToArray(); var netstream = client.GetStream(); netstream.Write(fileBytes, 0, fileBytes.Length); netstream.Close(); client.Close();
取得查詢結果並回傳至聊天室
將接收到的stream轉為byte。
1 2 3 4 5 6 7 8 9 10 11 12 13
int totalrecbytes = 0; var result = new MemoryStream(); int recBytes; byte[] recData = newbyte[1000]; while ((recBytes = stream.Read(recData, 0, recData.Length)) > 0) { result.Write(recData, 0, recBytes); totalrecbytes += recBytes; } result.Close(); stream.Close(); tcpClient.Close(); return result.ToArray();