基本上我正在编写一个小的Windows应用程序来发送,我不知道如何通过TCP套接字向本地网络机器发送命令。我在谷歌中查找的所有示例看起来都很复杂,我想要做的事情。到目前为止,我在我的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 request
发送到网站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());
}
答案 0 :(得分:3)
看起来您只想制作网络请求,而不是学习TCP通信。以下是您可以使用的部分类列表:
在Framework和JavaScriptSerializer中也有处理JSON的课程以及JSON.Net以外的其他课程是最知名的。
显然你可以更深入地直接使用System.Net命名空间的TCP方法,但这种情况可能有点过分。
答案 1 :(得分:1)
我会在IIS中设置一个TCP / IP WCF服务。如果您不想使用IIS,它也可以在Windows服务/控制台应用程序/ WinForm应用程序中自行托管它。
然后,您可以从服务中返回任意格式 - 包括JSON