如何发送和接收原始JSON
本文关键字:原始 JSON 何发送 | 更新日期: 2023-09-27 18:26:43
我需要一些帮助来确定这个方向。我只需要程序在给定的IP和端口向服务器发送一个固定的原始简单JSON格式的消息,然后它需要在给定的端口上侦听响应,然后将原始响应写入控制台。
我发现了一些关于处理JSONhttp请求的主题,但我认为我没有走上正轨。这是我正在尝试调整的代码。
public static void send_json()
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://10.211.55.5:7752");
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
request.Method = "POST";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write("{'"request'": '"get_menu'", '"checksum'": '"'", '"table_state'": {'"table_id'": '"1'", '"waiter_id'": '"1001'"}}");
}
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
string json = "";
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
json += reader.ReadLine();
}
Console.Write(json);
}
}
下面的代码终于工作了!谢谢你们给我指明了正确的方向!
private void pos_test_button_Click(object sender, EventArgs e)
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket.Connect("127.0.0.1", 7777);
string get_menu_request = "{'"request'": '"get_menu'"}";
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(get_menu_request);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string _returndata = System.Text.Encoding.ASCII.GetString(inStream);
test_log_box.AppendText("'r'n'r'nPOS Connection Test: " + "'r'n" + _returndata);
}