基本上我正在编写一个要发送的小型 Windows 应用程序,但我不确定如何通过 TCP 套接字将命令发送到本地网络机器。我在 google 中查找的所有示例对于我想要做的事情来说看起来都很复杂。到目前为止,我的 c# 程序中有这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
namespace MiningMonitorClientW
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new form1());
string userworker = Textbox1 + TextBox2;
}
public static string Textbox1 { get; set; }
public static string TextBox2 { get; set; }
}
}
基本上我正在尝试在 C# 中模拟我在下面的 ruby 中的这段代码
通过 TCPsocket 向给定 IP 发送命令,然后保存响应,即 json。
s = TCPSocket.new '192.xxx.x.x', xxxx
s.puts '{"command": "devs"}'
dev_query = s.gets
然后使用 http put 请求发送到网站
path = "/workers/update"
host = "https://miningmonitor.herokuapp.com"
puts RestClient.put "#{host}#{path}", updateinfo, {:content_type => :json}
我很想在 c# 中有人帮助我!!!1 :D 谢谢!
好吧,我最终解决了我的问题,下面的代码通过 TCP 发送一个字符串,然后在字符串中接收一个 json。
byte[] bytes = new byte[1024];
try
{
IPAddress ipAddr = IPAddress.Parse("xxx.xxx.x.xxx");
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4028);
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(ipEndPoint);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
string SummaryMessage = "string to send";
byte[] msg = Encoding.ASCII.GetBytes(SummaryMessage);
sender.Send(msg);
byte[] buffer = new byte[1024];
int lengthOfReturnedBuffer = sender.Receive(buffer);
char[] chars = new char[lengthOfReturnedBuffer];
Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, lengthOfReturnedBuffer, chars, 0);
String returnedJson = new String(chars);
Console.WriteLine("The Json:{0}", returnedJson);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.ToString());
}