1) Json 파일 읽기 

 

파일 내용 - device.json 

{  "deviceInfo":[
      {"device":"DEVICE_069", "hostname":"127.0.0.1", "port":9010},
      {"device":"DEVICE_083", "hostname":"127.0.0.1", "port":9020},
      {"device":"DEVICE_015", "hostname":"127.0.0.1", "port":9030}
   ]
}

코드에서 파일 읽기 
class DeviceInfo
{
    public string device = null;
    public string hostname = null;
    public int port = 0;
}
static Dictionary<string, DeviceInfo> dicDeviceInfo = new Dictionary<string, DeviceInfo>();

JObject jObj = JObject.Parse(File.ReadAllText(".\\INFO\\DEVICE.JSON"));
foreach (JObject device in jObj["deviceInfo"])
{
    DeviceInfo deviceInfo = device.ToObject<DeviceInfo>();
    dicDeviceInfo.Add(deviceInfo.device, deviceInfo);
}


파일 내용 -  server_command.json 
{  "serverCommandInfo":[
      {"command":"CMD_001", "forwardCommand":"CMD_001_A"},
      {"command":"CMD_002", "forwardCommand":"CMD_002_B"}
   ]
}

코드에서 파일읽기 

static Dictionary<string, string> CmdInfo = new Dictionary<string, string>();

JObject jObj = JObject.Parse(File.ReadAllText(".\\INFO\\SERVER_COMMAND.JSON"));
 foreach (JObject cmd in jObj["serverCommandInfo"])
 {
     CmdInfo[cmd["command"].ToString()] = cmd["forwardCommand"].ToString();
 }
}

코드로 Json 파일 쓰기 
 using (StreamWriter file = File.CreateText("sample.json"))
 {
     JsonSerializer serializer = new JsonSerializer();
     serializer.Serialize(file, jsonObj);
 }

코드로 Json 파일 쓰기 2 
string path = Application.StartupPath + @"\Config.json";
string[] userList = new string[4] { "USER1", "USER2", "USER3", "USER4" };
string users = string.Empty;
JObject configData = new JObject(
    new JProperty("IP", "127.0.0.1"),
    new JProperty("PORT", "8088"),
    new JProperty("DATABASE", "DB TEST"),
    new JProperty("ID", "TestID"),
    new JProperty("PASSWORD", "1234")
    );

// Jarray 로 추가
configData.Add("USERS", JArray.FromObject(userList));

// 파일 생성 후 쓰기
File.WriteAllText(path, configData.ToString());

 

 


[시나리오][Server] Request 송신 (URI:http://127.0.0.1:8010/fromServer, Body:{"command":"CMD_001","targetDevice":["DEVICE_069"],"param":"fe303904"})
[시나리오][DEVICE_069] Request 수신 (URI:http://127.0.0.1:9010/fromEdge, Body:{
  "command": "CMD_001_A",
  "param": "fe303904"
})
[시나리오][DEVICE_069] Response 송신 (Status Code:200, Body:{"result":["20b95f9c"]})
[시나리오][Server] Response 수신 (Status Code:200, Body:{
  "result": [
    "20b95f9c"
  ]
}, Elapsed time:1,380ms)

[시나리오][Server] Request 송신 (URI:http://127.0.0.1:8010/fromServer, Body:{"command":"CMD_002","targetDevice":["DEVICE_083","DEVICE_015"],"param":"ce3c39e1"})
[시나리오][DEVICE_083] Request 수신 (URI:http://127.0.0.1:9020/fromEdge, Body:{
  "command": "CMD_002_B",
  "param": "ce3c39e1"
})
[시나리오][DEVICE_083] Response 송신 (Status Code:200, Body:{"result":["c8d4fc55"]})
[시나리오][DEVICE_015] Request 수신 (URI:http://127.0.0.1:9030/fromEdge, Body:{
  "command": "CMD_002_B",
  "param": "ce3c39e1"
})
[시나리오][DEVICE_015] Response 송신 (Status Code:200, Body:{"result":["9604d2cd"]})
[시나리오][Server] Response 수신 (Status Code:200, Body:{
  "result": [
    "c8d4fc55",
    "9604d2cd"
  ]


 StreamReader sr = new StreamReader(context.Request.InputStream);
 JObject body = JObject.Parse(sr.ReadToEnd());
 sr.Close();
strRes = sendToDevices(body["command"].ToString(), body["param"].ToString(), body["targetDevice"].ToObject<List<string>>());

'프로그래밍 > C#' 카테고리의 다른 글

기본내용 - 네트워크  (0) 2025.06.01
기본내용  (0) 2025.06.01
sample #2 .. No 5  (0) 2025.06.01
sample #2 .. No 4  (0) 2025.06.01
sample #2 .. No 3  (0) 2025.05.31

 

1) 윈도우에서 포트가 사용중인지 확인 방법 

netstat에서 자주 사용되는 옵션(-a, -n, -o)

-a : 모든 포트를 표시해준다.
-n : "IP주소:포트" 형태로 보여준다.
      ex) 192.168.0.100:8080
-o : PID(프로세스ID)를 표시해준다.

전체에서 LISTEN 중인 포트를 확인하는 방법 
netstat -ano | find "LISTEN"

현재 Local 컴퓨터에 443포트로 접속한 ip 확인
> netstat -ano | find "특정 IP:443" ( "443" ) 

위에서 해당 IP의 포트를 사용하는 프로그램 확인 후 window 작업 관리자에서 종료 
tasklist | find "pid"

 

2) 네트워크 프로그램을 사용하기 위한 헤더들 

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using Systehttp://m.Net.Http;
using System.Text;
using System.Threading;

 

3) 서버에서 아래 내용 전송 시 각각의 값을 확인 하는 방법 

 

서버가 아래 전송 시 
Request 송신 (URI:http://127.0.0.1:8010/fromServer, Body:{"command":"CMD_001","targetDevice":["DEVICE_069"],"param":"fe303904"})

클라이언트는 아래에서 각각의 값을 확인할 수 있다. 

context.Request.HttpMethod -> POST 

context.Request.Url --> http://127.0.0.1:8010/fromServer

context.Request.RawUrl --> /fromServer

 StreamReader sr = new StreamReader(context.Request.InputStream);
JObject body = JObject.Parse(sr.ReadToEnd());
sr.Close();
-------------------------------> 아래 내요으로 읽어짐 
 {
  "command": "CMD_001",
  "targetDevice": [
    "DEVICE_069"
  ],
  "param": "fe303904"
}
-------------------------------

응답 보낼 때, 
--------------------------------------------
 if (strRes != null)
 {
     byte[] data = Encoding.UTF8.GetBytes(strRes);
     context.Response.OutputStream.Write(data, 0, data.Length);
 }
 context.Response.StatusCode = 200;
 context.Response.Close();
-----------------------------------------------

'프로그래밍 > C#' 카테고리의 다른 글

기본내용 - Json  (0) 2025.06.01
기본내용  (0) 2025.06.01
sample #2 .. No 5  (0) 2025.06.01
sample #2 .. No 4  (0) 2025.06.01
sample #2 .. No 3  (0) 2025.05.31

 

1) 입력 / 출력 

입력 
String line = Console.ReadLine();

출력 
Console.WriteLine(dev + ":" + CmdInfo[command] + "#" + param);

 

2) String 생성 예시 

파일 경로 
 string path = string.Format(".\\DEVICE\\REQ_TO_{0}.TXT", dev);

URL 경로 
string url = string.Format("http://{0}:{1}/fromEdge", dicDeviceInfo[device].hostname, dicDeviceInfo[device].port);

 

3) 출력 예시

Console.WriteLine(string.Format(">>>>>>>>>>>>>>[{0}] Request({1}) : {2}", DateTime.Now.ToString("hh:mm:ss.fff"), context.Request.HttpMethod, context.Request.Url));

 

4) 파일 쓰기 / 읽기 

 

파일을 읽어서 한줄씩 확인 

   -. 문장 읽을 때, TrimEnd() 는 문장 뒤쪽 공백 제거 .. 그럼 TrimStart 는 앞쪽 공백 제거, , Trim()는 앞뒤모두 공백 제거 

( 참고로 Trim(char) 를 사용하면 해당 char 문자를 문장 앞뒤고 제거함 )

예제 1)  
string[] lines = File.ReadAllLines(".\\INFO\\SERVER_COMMAND.TXT");

 foreach (string one in lines)
 {
     string[] wds = one.Split('#');
     CmdInfo[wds[0]] = wds[1];
 }

예제 2) 
string res = "";
foreach( string dev in devices)
{
    string path = string.Format(".\\DEVICE\\RES_FROM_{0}.TXT", dev);
    string devicesRes = File.ReadAllText(path).TrimEnd();

    if(res == "")
    {
        res = devicesRes;
    }else
    {
        res += ("," + devicesRes);
    }
}

 

파일 생성 후 한줄씩 쓰기 

 foreach (string dev in devices)
 {
     string path = string.Format(".\\DEVICE\\REQ_TO_{0}.TXT", dev);
     File.WriteAllText(path, string.Format("{0}#{1}", cmdDevice, param));
 }

 

5) 문자열에서 특정 위치 찾기 

IndexOf : 문자열에서 찾고자 하는 특정 문자 또는 문자열의 인덱스 번호 출력 (존재하지 않으면 -1)
   > str = "ABCDEFG" 일 경우 str. IndexOf("EF") 라면 4 출력 
LastIndexOf : 문자열에서 찾고자 하는 문자 또는 문자열이 중복될 때, 가장 마지막에 인덱스 번호 출력 (존재하지 않으면 -1)
Contains : 문자열에서 찾고자 하는 문자 또는 문자열의 존재 여부 확인 (true,false 반환)

 

6) 특정 문자 변경 

Replace 사용해서 변경 가능 

참고 링크 : https://myoung-min.tistory.com/51
참고 링크 : https://wowgame.tistory.com/3

'프로그래밍 > C#' 카테고리의 다른 글

기본내용 - Json  (0) 2025.06.01
기본내용 - 네트워크  (0) 2025.06.01
sample #2 .. No 5  (0) 2025.06.01
sample #2 .. No 4  (0) 2025.06.01
sample #2 .. No 3  (0) 2025.05.31

 

workflow.json

{
  "workflow": {
    "workflow1": {
      "startFrom": "create",
      "state": {
        "create": {
          "type": "action",
          "url": "http://127.0.0.1:8011/create",
          "parameters": [ "id" ],
          "next": "add"
        },
        "add": {
          "type": "action",
          "url": "http://127.0.0.1:8012/add",
          "parameters": [ "id", "key", "data" ],
          "next": "fetch"
        },
        "fetch": {
          "type": "action",
          "url": "http://127.0.0.1:8013/fetch",
          "parameters": [],
          "next": "end"
        }
      },
      "responses": [ "id", "total" ]
    },
    "workflow3": {
      "startFrom": "create",
      "state": {
        "create": {
          "type": "action",
          "url": "http://127.0.0.1:9010/create",
          "parameters": [ "queuesize" ],
          "next": "add"
        },
        "add": {
          "type": "parallel",
          "branches": [
            {
              "startFrom": "getdata",
              "state": {
                "getdata": {
                  "type": "action",
                  "url": "http://127.0.0.1:9011/getdata",
                  "parameters": [ "id" ],
                  "next": "adddata"
                },
                "adddata": {
                  "type": "action",
                  "url": "http://127.0.0.1:9012/adddata",
                  "parameters": [ "queueid", "data" ],
                  "next": "end"
                }
              },
              "responses": []
            },
            {
              "startFrom": "addmedia",
              "state": {
                "addmedia": {
                  "type": "action",
                  "url": "http://127.0.0.1:9013/addmedia",
                  "parameters": [ "queueid", "mediaid" ],
                  "next": "end"
                }
              },
              "responses": []
            }
          ],
          "next": "check"
        },
        "check": {
          "type": "choice",
          "choices": [
            {
              "variable": "result",
              "equal": "fail",
              "next": "error"
            },
            {
              "variable": "queuetotal",
              "equal": "3",
              "next": "end"
            }
          ],
          "next": "add"
        },
        "error": {
          "type": "action",
          "url": "http://127.0.0.1:9014/error",
          "parameters": [ "queueid", "queuetotal", "errorcode" ],
          "next": "end"
        }
      },
      "responses": [ "queueid", "queuetotal", "result" ]
    }
  }
}

 

variable.json

{
  "id": "100a",
  "key": "none",
  "data": "data0001",
  "total": "0",
  "queueid": "q001",
  "queuesize": "10",
  "queuetotal": "0",
  "mediaid": "media001",
  "result": "ok",
  "errorcode": "none"
}

 

workflow.cs

using System;
using System.Collections.Generic;
using System.Linq;

namespace SP_TEST
{
    class Workflow
    {
        public string startFrom;
        public List<string> responses;
        public Dictionary<string, State> state = new Dictionary<string, State>();

        public Dictionary<string, string> Run(Dictionary<string, string> Variable)
        {
            string next = startFrom;
            do
            {
                next = state[next].Run(Variable);
            } while (next != "end");

            // make response
            return Variable.Where(s => responses.Contains(s.Key)).ToDictionary(dict => dict.Key, dict => dict.Value);
        }
    }
}

 

state.cs

using System;
using System.Collections.Generic;
using System.Linq;
using Systehttp://m.Net.Http;
using Newtonsoft.Json.Linq;
using Systehttp://m.Threading.Tasks;

namespace SP_TEST
{
    class State
    {
        public string type;
        public string url;              // action
        public List<string> parameters; // action
        public List<Workflow> branches; // parallel
        public List<Choice> choices;    // choice
        public string next;

        public class Choice
        {
            public string variable;
            public string equal;
            public string next;
        }


        public string Run(Dictionary<string, string> Variable)
        {
            // Run state and update values
            if (type == "action")
            {
                HttpClient client = new HttpClient();
                var query = string.Join("&", parameters.Select(t => t += "=" + Variable[t]));
                string uri = parameters.Count > 0 ? url + "?" + query : url;
                HttpResponseMessage result = client.GetAsync(uri).Result;
                string resultstr = result.Content.ReadAsStringAsync().Result;
                var response = JObject.Parse(resultstr).ToObject<Dictionary<string, string>>();
                // update variables
                foreach (var pair in response)
                {
                    Variable[pair.Key] = pair.Value;
                    Console.WriteLine($"Update variable {pair.Key} to {pair.Value}");
                }
                client.Dispose();
            }
            else if (type == "parallel")
            {
                List<Task> list = new List<Task>();
                foreach (Workflow w in branches)
                {
                    Task task = Task.Run(() => w.Run(Variable));
                    list.Add(task);
                }
                Task.WaitAll(list.ToArray());
            }
            else if (type == "choice")
            {
                foreach (Choice c in choices)
                {
                    Console.WriteLine($"Check {c.variable} equals {c.equal}");
                    if (Variable[c.variable] == c.equal)
                    {
                        Console.WriteLine($"Satisfied choice! move to {c.next}");
                        return c.next;
                    }
                }
            }
            Console.WriteLine($"Move to {next}");
            return next;
        }
    }
}

 

program.cs

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;

namespace SP_TEST
{
    class Program
    {
        const string cWorkflowFile = "WORKFLOW.JSON";
        const string cVariableFile = "VARIABLE.JSON";
        static Dictionary<string, string> Variable = new Dictionary<string, string>();
        static Dictionary<string, Workflow> Workflow = new Dictionary<string, Workflow>();

        static void Main(string[] args)
        {
            // Variable 파싱
            JObject var_json = JObject.Parse(File.ReadAllText(cVariableFile));
            Variable = var_json.ToObject<Dictionary<string, string>>();

            // Workflow 파싱
            JObject workflow_json = JObject.Parse(File.ReadAllText(cWorkflowFile));
            Workflow = workflow_json["workflow"].ToObject<Dictionary<string, Workflow>>();

            // HTTP 서버 시작
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://127.0.0.1:8080/");
            listener.Start();
            while (true)
            {
                var context = listener.GetContext();
                string workflowname = context.Request.Url.Segments[1].TrimEnd('/');
                // Workflow 실행
                var response = Workflow[workflowname].Run(Variable);
                var bytes = Encoding.UTF8.GetBytes(JObject.FromObject(response).ToString());
                context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                context.Response.StatusCode = 200;
                context.Response.Close();
            }
        }
    }
}

'프로그래밍 > C#' 카테고리의 다른 글

기본내용 - 네트워크  (0) 2025.06.01
기본내용  (0) 2025.06.01
sample #2 .. No 4  (0) 2025.06.01
sample #2 .. No 3  (0) 2025.05.31
sample #2 .. No 2  (0) 2025.05.31

 

workflow.json 

{
  "workflow": {
    "workflow1": {
      "startFrom": "create",
      "state": {
        "create": {
          "type": "action",
          "url": "http://127.0.0.1:8011/create",
          "parameters": [ "id" ],
          "next": "add"
        },
        "add": {
          "type": "action",
          "url": "http://127.0.0.1:8012/add",
          "parameters": [ "id", "key", "data" ],
          "next": "fetch"
        },
        "fetch": {
          "type": "action",
          "url": "http://127.0.0.1:8013/fetch",
          "parameters": [],
          "next": "end"
        }
      },
      "responses": [ "id", "total" ]
    },
    "workflow2": {
      "startFrom": "create",
      "state": {
        "create": {
          "type": "action",
          "url": "http://127.0.0.1:9010/create",
          "parameters": [ "queuesize" ],
          "next": "add"
        },
        "add": {
          "type": "parallel",
          "branches": [
            {
              "startFrom": "getdata",
              "state": {
                "getdata": {
                  "type": "action",
                  "url": "http://127.0.0.1:9011/getdata",
                  "parameters": [ "id" ],
                  "next": "adddata"
                },
                "adddata": {
                  "type": "action",
                  "url": "http://127.0.0.1:9012/adddata",
                  "parameters": [ "queueid", "data" ],
                  "next": "end"
                }
              },
              "responses": []
            },
            {
              "startFrom": "addmedia",
              "state": {
                "addmedia": {
                  "type": "action",
                  "url": "http://127.0.0.1:9013/addmedia",
                  "parameters": [ "queueid", "mediaid" ],
                  "next": "end"
                }
              },
              "responses": []
            }
          ],
          "next": "report"
        },
        "report": {
          "type": "action",
          "url": "http://127.0.0.1:9014/report",
          "parameters": [ "result", "errorcode", "queuetotal" ],
          "next": "end"
        }
        
      },
      "responses": [ "queueid", "queuetotal", "result" ]
    }
  }
}

 

variable.json

{
  "id": "100a",
  "key": "none",
  "data": "data0001",
  "total": "0",
  "queueid": "q001",
  "queuesize": "10",
  "queuetotal": "0",
  "mediaid": "media001",
  "result": "ok",
  "errorcode": "none"
}

 

 

program.cs

class Program
    {
        const string cWorkflowFile = "WORKFLOW.JSON";
        const string cVariableFile = "VARIABLE.JSON";
        static Dictionary<string, string> Variable = new Dictionary<string, string>();
        static Dictionary<string, Workflow> Workflow = new Dictionary<string, Workflow>();

        static void Main(string[] args)
        {
            // Variable 파싱
            JObject var_json = JObject.Parse(File.ReadAllText(cVariableFile));
            Variable = var_json.ToObject<Dictionary<string, string>>();

            // Workflow 파싱
            JObject workflow_json = JObject.Parse(File.ReadAllText(cWorkflowFile));
            Workflow = workflow_json["workflow"].ToObject<Dictionary<string, Workflow>>();

            // HTTP 서버 시작
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://127.0.0.1:8080/");
            listener.Start();
            while (true)
            {
                var context = listener.GetContext();
                string workflowname = context.Request.Url.Segments[1].TrimEnd('/');
                // Workflow 실행
                var response = Workflow[workflowname].Run(Variable);
                var bytes = Encoding.UTF8.GetBytes(JObject.FromObject(response).ToString());
                context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                context.Response.StatusCode = 200;
                context.Response.Close();
            }
        }
    }

 

state.cs

class State
    {
        public string type;
        public string url;              // action
        public List<string> parameters; // action
        public List<Workflow> branches; // parallel
        public string next;

        public string Run(Dictionary<string, string> Variable)
        {
            // Run state and update values
            if (type == "action")
            {
                HttpClient client = new HttpClient();
                var query = string.Join("&", parameters.Select(t => t += "=" + Variable[t]));
                string uri = parameters.Count > 0 ? url + "?" + query : url;
                HttpResponseMessage result = client.GetAsync(uri).Result;
                string resultstr = result.Content.ReadAsStringAsync().Result;
                var response = JObject.Parse(resultstr).ToObject<Dictionary<string, string>>();
                // update variables
                foreach (var pair in response)
                {
                    Variable[pair.Key] = pair.Value;
                    Console.WriteLine($"Update variable {pair.Key} to {pair.Value}");
                }
                client.Dispose();
            }
            else if (type == "parallel")
            {
                List<Task> list = new List<Task>();
                foreach (Workflow w in branches)
                {
                    Task task = Task.Run(() => w.Run(Variable));
                    list.Add(task);
                }
                Task.WaitAll(list.ToArray());
            }
            Console.WriteLine($"Move to {next}");
            return next;
        }
    }

 

workflow.cs

class Workflow
    {
        public string startFrom;
        public List<string> responses;
        public Dictionary<string, State> state = new Dictionary<string, State>();

        public Dictionary<string, string> Run(Dictionary<string, string> Variable)
        {
            string next = startFrom;
            do
            {
                next = state[next].Run(Variable);
            } while (next != "end");

            // make response
            return Variable.Where(s => responses.Contains(s.Key)).ToDictionary(dict => dict.Key, dict => dict.Value);
        }
    }

'프로그래밍 > C#' 카테고리의 다른 글

기본내용  (0) 2025.06.01
sample #2 .. No 5  (0) 2025.06.01
sample #2 .. No 3  (0) 2025.05.31
sample #2 .. No 2  (0) 2025.05.31
sample #2 .. No 1  (0) 2025.05.31

VARIABLE.JSON

{
  "id": "100a",
  "key": "none",
  "data": "data0001",
  "total": "0"
}

 

 

STATE.json 

{
  "state": 
  {
    "create": {
      "type": "action",
      "url": "http://127.0.0.1:8011/create",
      "parameters": [ "id" ]
    },
    "add": {
      "type": "action",
      "url": "http://127.0.0.1:8012/add",
      "parameters": [ "id", "key", "data" ]
    },
    "fetch": {
      "type": "action",
      "url": "http://127.0.0.1:8013/fetch",
      "parameters": []
    }
  }

}

 

 

program.cs

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;

namespace SP_TEST
{
    class Program
    {
const string cWorkflowFile = "WORKFLOW.JSON";
        const string cVariableFile = "VARIABLE.JSON";
        static Dictionary<string, string> Variable = new Dictionary<string, string>();
        static Dictionary<string, Workflow> Workflow = new Dictionary<string, Workflow>();

        static void Main(string[] args)
        {
            // Variable 파싱
            JObject var_json = JObject.Parse(File.ReadAllText(cVariableFile));
            Variable = var_json.ToObject<Dictionary<string, string>>();

            // Workflow 파싱
            JObject workflow_json = JObject.Parse(File.ReadAllText(cWorkflowFile));
            Workflow = workflow_json["workflow"].ToObject<Dictionary<string, Workflow>>();

            // HTTP 서버 시작
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://127.0.0.1:8080/");
            listener.Start();
            while (true)
            {
                var context = listener.GetContext();
                string workflowname = context.Request.Url.Segments[1].TrimEnd('/');
                // Workflow 실행
                var response = Workflow[workflowname].Run(Variable);
                var bytes = Encoding.UTF8.GetBytes(JObject.FromObject(response).ToString());
                context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                context.Response.StatusCode = 200;
                context.Response.Close();
            }
        }
 }
}

 

state.cs 

namespace SP_TEST
{
    class State
    {
        public string type;
        public string url;              // action
        public List<string> parameters; // action
        public List<Workflow> branches; // parallel
        public List<Choice> choices;    // choice
        public string next;

        public class Choice
        {
            public string variable;
            public string equal;
            public string next;
        }


        public string Run(Dictionary<string, string> Variable)
        {
            // Run state and update values
            if (type == "action")
            {
                HttpClient client = new HttpClient();
                var query = string.Join("&", parameters.Select(t => t += "=" + Variable[t]));
                string uri = parameters.Count > 0 ? url + "?" + query : url;
                HttpResponseMessage result = client.GetAsync(uri).Result;
                string resultstr = result.Content.ReadAsStringAsync().Result;
                var response = JObject.Parse(resultstr).ToObject<Dictionary<string, string>>();
                // update variables
                foreach (var pair in response)
                {
                    Variable[pair.Key] = pair.Value;
                    Console.WriteLine($"Update variable {pair.Key} to {pair.Value}");
                }
                client.Dispose();
            }
            else if (type == "parallel")
            {
                List<Task> list = new List<Task>();
                foreach (Workflow w in branches)
                {
                    Task task = Task.Run(() => w.Run(Variable));
                    list.Add(task);
                }
                Task.WaitAll(list.ToArray());
            }
            else if (type == "choice")
            {
                foreach (Choice c in choices)
                {
                    Console.WriteLine($"Check {c.variable} equals {c.equal}");
                    if (Variable[c.variable] == c.equal)
                    {
                        Console.WriteLine($"Satisfied choice! move to {c.next}");
                        return c.next;
                    }
                }
            }
            Console.WriteLine($"Move to {next}");
            return next;
        }
    }
}

'프로그래밍 > C#' 카테고리의 다른 글

sample #2 .. No 5  (0) 2025.06.01
sample #2 .. No 4  (0) 2025.06.01
sample #2 .. No 2  (0) 2025.05.31
sample #2 .. No 1  (0) 2025.05.31
이것저것  (0) 2024.06.12

 

VARIABLE.TXT

id#100a
data#data0001

 

STATE.TXT

create#action#http://127.0.0.1:8011/create#id
add#action#http://127.0.0.1:8012/add#id,data
fetch#action#http://127.0.0.1:8013/fetch#

const string cStateFile = "STATE.TXT";
        const string cVariableFile = "VARIABLE.TXT";

        static void Main(string[] args)
        {
            Dictionary<string, string> Variable = new Dictionary<string, string>();
            Dictionary<string, string> State = new Dictionary<string, string>();

            // Variable 파싱
            foreach (var line in File.ReadAllLines(cVariableFile))
            {
                var str = line.Split('#');
                var name = str[0];
                var value = str[1];
                Variable[name] = value;
            }

            // State 파싱
            foreach (var line in File.ReadAllLines(cStateFile))
            {
                var str = line.Split('#');
                var name = str[0];
                var action = str[1];
                var url = str[2];
                var vars = str[3].Split(',').ToList();
                if (vars[0] == "") vars.Clear();    // Parameter 없는 경우 clear
                var query = vars.Select(t => t += "=" + Variable[t]);
                if (vars.Count > 0)
                {
                    State[name] = action + " " + url + "?" + string.Join("&", query);
                }
                else
                {
                    State[name] = action + " " + url;
                }
            }

            string cmd;
            while ((cmd = Console.ReadLine()) != null)
            {
                Console.WriteLine(State[cmd]);
            }

'프로그래밍 > C#' 카테고리의 다른 글

sample #2 .. No 4  (0) 2025.06.01
sample #2 .. No 3  (0) 2025.05.31
sample #2 .. No 1  (0) 2025.05.31
이것저것  (0) 2024.06.12
클라이언트 서버 예제 3  (0) 2024.05.14

 

--------------------

STATE.TXT 

create#action#http://127.0.0.1:8011/create
add#action#http://127.0.0.1:8012/add
fetch#action#http://127.0.0.1:8013/fetch

----------------------

const string cStateFile = "STATE.TXT";

        static void Main(string[] args)
        {
            Dictionary<string, string> State = new Dictionary<string, string>();</string, string></string, string>
            foreach (var line in File.ReadAllLines(cStateFile))
            {
                var str = line.Split('#');
                var name = str[0];
                var action = str[1];
                var url = str[2];
                State[name] = action + " " + url;
            }

            string cmd;
            while ((cmd = Console.ReadLine()) != null)
            {
                Console.WriteLine(State[cmd]);
            }

        }

 

나눠서 볼 것 

 

1)
Dictionary<string, string> State = new Dictionary<string, string>();


2) 
while ((cmd = Console.ReadLine()) != null)
{
Console.WriteLine(State[cmd]);
}

3) 
const string cStateFile = "STATE.TXT";

foreach (var line in File.ReadAllLines(cStateFile))

4) 
// line //
create#action#http://127.0.0.1:8011/create
add#action#http://127.0.0.1:8012/add
fetch#action#http://127.0.0.1:8013/fetch
//

var str = line.Split('#');
var name = str[0];
var action = str[1];
var url = str[2];
State[name] = action + " " + url;

'프로그래밍 > C#' 카테고리의 다른 글

sample #2 .. No 3  (0) 2025.05.31
sample #2 .. No 2  (0) 2025.05.31
이것저것  (0) 2024.06.12
클라이언트 서버 예제 3  (0) 2024.05.14
클라이언트 서버 예제 2  (0) 2024.05.14

netstat -ano

 

 

class Program
    {
        const string cStateFile = "STATE.TXT";

        static void Main(string[] args)
        {
            Dictionary<string, string> State = new Dictionary<string, string>();
            foreach (var line in File.ReadAllLines(cStateFile))
            {
                var str = line.Split('#');
                var name = str[0];
                var action = str[1];
                var url = str[2];
                State[name] = action + " " + url;
            }

            string cmd;
            while ((cmd = Console.ReadLine()) != null)
            {
                Console.WriteLine(State[cmd]);
            }

        }
    }

 

class Program
    {
        const string cStateFile = "STATE.TXT";
        const string cVariableFile = "VARIABLE.TXT";

        static void Main(string[] args)
        {
            Dictionary<string, string> Variable = new Dictionary<string, string>();
            Dictionary<string, string> State = new Dictionary<string, string>();

            // Variable 파싱
            foreach (var line in File.ReadAllLines(cVariableFile))
            {
                var str = line.Split('#');
                var name = str[0];
                var value = str[1];
                Variable[name] = value;
            }

            // State 파싱
            foreach (var line in File.ReadAllLines(cStateFile))
            {
                var str = line.Split('#');
                var name = str[0];
                var action = str[1];
                var url = str[2];
                var vars = str[3].Split(',').ToList();
                if (vars[0] == "") vars.Clear();    // Parameter 없는 경우 clear
                var query = vars.Select(t => t += "=" + Variable[t]);
                if (vars.Count > 0)
                {
                    State[name] = action + " " + url + "?" + string.Join("&", query);
                }
                else
                {
                    State[name] = action + " " + url;
                }
            }

            string cmd;
            while ((cmd = Console.ReadLine()) != null)
            {
                Console.WriteLine(State[cmd]);
            }

        }
    }

 

class Program
    {
        const string cStateFile = "STATE.JSON";
        const string cVariableFile = "VARIABLE.JSON";
        static Dictionary<string, string> Variable = new Dictionary<string, string>();
        static Dictionary<string, State> State = new Dictionary<string, State>();

        static void Main(string[] args)
        {
            // Variable 파싱
            JObject var_json = JObject.Parse(File.ReadAllText(cVariableFile));
            Variable = var_json.ToObject<Dictionary<string, string>>();

            // State 파싱
            JObject state_json = JObject.Parse(File.ReadAllText(cStateFile));
            State = state_json["state"].ToObject<Dictionary<string, State>>();

            // HTTP 서버 시작
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://127.0.0.1:8080/");
            listener.Start();
            while (true)
            {
                var context = listener.GetContext();
                string statename = context.Request.Url.Segments[1].TrimEnd('/');
                // State 실행
                State[statename].Run(Variable);
                context.Response.StatusCode = 200;
                context.Response.Close();
            }
        }
    }


class State
    {
        public string type;
        public string url;
        public List<string> parameters;

        public void Run(Dictionary<string, string> Variable)
        {
            // ActionState : Call Microservice
            HttpClient client = new HttpClient();
            var query = string.Join("&", parameters.Select(t => t += "=" + Variable[t]));
            string uri = parameters.Count > 0 ? url + "?" + query : url;
            HttpResponseMessage result = client.GetAsync(uri).Result;
            string resultstr = result.Content.ReadAsStringAsync().Result;
            var response = JObject.Parse(resultstr).ToObject<Dictionary<string, string>>();

            // update variables
            foreach (var pair in response)
            {
                Variable[pair.Key] = pair.Value;
                Console.WriteLine($"Update variable {pair.Key} to {pair.Value}");
            }
            client.Dispose();
        }
    }

 

class Program
    {
        const string cWorkflowFile = "WORKFLOW.JSON";
        const string cVariableFile = "VARIABLE.JSON";
        static Dictionary<string, string> Variable = new Dictionary<string, string>();
        static Dictionary<string, Workflow> Workflow = new Dictionary<string, Workflow>();

        static void Main(string[] args)
        {
            // Variable 파싱
            JObject var_json = JObject.Parse(File.ReadAllText(cVariableFile));
            Variable = var_json.ToObject<Dictionary<string, string>>();

            // Workflow 파싱
            JObject workflow_json = JObject.Parse(File.ReadAllText(cWorkflowFile));
            Workflow = workflow_json["workflow"].ToObject<Dictionary<string, Workflow>>();

            // HTTP 서버 시작
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://127.0.0.1:8080/");
            listener.Start();
            while (true)
            {
                var context = listener.GetContext();
                string workflowname = context.Request.Url.Segments[1].TrimEnd('/');
                // Workflow 실행
                var response = Workflow[workflowname].Run(Variable);
                var bytes = Encoding.UTF8.GetBytes(JObject.FromObject(response).ToString());
                context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                context.Response.StatusCode = 200;
                context.Response.Close();
            }
        }
    }

class State
    {
        public string type;
        public string url;              // action
        public List<string> parameters; // action
        public List<Workflow> branches; // parallel
        public string next;

        public string Run(Dictionary<string, string> Variable)
        {
            // Run state and update values
            if (type == "action")
            {
                HttpClient client = new HttpClient();
                var query = string.Join("&", parameters.Select(t => t += "=" + Variable[t]));
                string uri = parameters.Count > 0 ? url + "?" + query : url;
                HttpResponseMessage result = client.GetAsync(uri).Result;
                string resultstr = result.Content.ReadAsStringAsync().Result;
                var response = JObject.Parse(resultstr).ToObject<Dictionary<string, string>>();
                // update variables
                foreach (var pair in response)
                {
                    Variable[pair.Key] = pair.Value;
                    Console.WriteLine($"Update variable {pair.Key} to {pair.Value}");
                }
                client.Dispose();
            }
            else if (type == "parallel")
            {
                List<Task> list = new List<Task>();
                foreach (Workflow w in branches)
                {
                    Task task = Task.Run(() => w.Run(Variable));
                    list.Add(task);
                }
                Task.WaitAll(list.ToArray());
            }
            Console.WriteLine($"Move to {next}");
            return next;
        }
    }

 

   class Program
    {
        const string cWorkflowFile = "WORKFLOW.JSON";
        const string cVariableFile = "VARIABLE.JSON";
        static Dictionary<string, string> Variable = new Dictionary<string, string>();
        static Dictionary<string, Workflow> Workflow = new Dictionary<string, Workflow>();

        static void Main(string[] args)
        {
            // Variable 파싱
            JObject var_json = JObject.Parse(File.ReadAllText(cVariableFile));
            Variable = var_json.ToObject<Dictionary<string, string>>();

            // Workflow 파싱
            JObject workflow_json = JObject.Parse(File.ReadAllText(cWorkflowFile));
            Workflow = workflow_json["workflow"].ToObject<Dictionary<string, Workflow>>();

            // HTTP 서버 시작
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://127.0.0.1:8080/");
            listener.Start();
            while (true)
            {
                var context = listener.GetContext();
                string workflowname = context.Request.Url.Segments[1].TrimEnd('/');
                // Workflow 실행
                var response = Workflow[workflowname].Run(Variable);
                var bytes = Encoding.UTF8.GetBytes(JObject.FromObject(response).ToString());
                context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                context.Response.StatusCode = 200;
                context.Response.Close();
            }
        }
    }

class State
    {
        public string type;
        public string url;              // action
        public List<string> parameters; // action
        public List<Workflow> branches; // parallel
        public List<Choice> choices;    // choice
        public string next;

        public class Choice
        {
            public string variable;
            public string equal;
            public string next;
        }


        public string Run(Dictionary<string, string> Variable)
        {
            // Run state and update values
            if (type == "action")
            {
                HttpClient client = new HttpClient();
                var query = string.Join("&", parameters.Select(t => t += "=" + Variable[t]));
                string uri = parameters.Count > 0 ? url + "?" + query : url;
                HttpResponseMessage result = client.GetAsync(uri).Result;
                string resultstr = result.Content.ReadAsStringAsync().Result;
                var response = JObject.Parse(resultstr).ToObject<Dictionary<string, string>>();
                // update variables
                foreach (var pair in response)
                {
                    Variable[pair.Key] = pair.Value;
                    Console.WriteLine($"Update variable {pair.Key} to {pair.Value}");
                }
                client.Dispose();
            }
            else if (type == "parallel")
            {
                List<Task> list = new List<Task>();
                foreach (Workflow w in branches)
                {
                    Task task = Task.Run(() => w.Run(Variable));
                    list.Add(task);
                }
                Task.WaitAll(list.ToArray());
            }
            else if (type == "choice")
            {
                foreach (Choice c in choices)
                {
                    Console.WriteLine($"Check {c.variable} equals {c.equal}");
                    if (Variable[c.variable] == c.equal)
                    {
                        Console.WriteLine($"Satisfied choice! move to {c.next}");
                        return c.next;
                    }
                }
            }
            Console.WriteLine($"Move to {next}");
            return next;
        }
    }

'프로그래밍 > C#' 카테고리의 다른 글

sample #2 .. No 2  (0) 2025.05.31
sample #2 .. No 1  (0) 2025.05.31
클라이언트 서버 예제 3  (0) 2024.05.14
클라이언트 서버 예제 2  (0) 2024.05.14
서버 클라이언트 예제 1  (0) 2024.05.14

 

서버 > 중간프로그램 > 디바이스 로 전송/수신 되는 프로그램이며, 

외부 프로그램은 서버와  디바이스이고, 중간프로그램이 아래 동작 코드이다. 

 

아래 코드는 서버에서 아래 형태의 Json 데이터를 받으면 

{"command":"CMD_002","targetDevice":["DEVICE_083","DEVICE_015"],"param":"ce3c39e1"}

 

device.json 파일에서 아래 정보를 읽은 후 

{  "deviceInfo":[
      {"device":"DEVICE_069", "hostname":"127.0.0.1", "port":9010},
      {"device":"DEVICE_083", "hostname":"127.0.0.1", "port":9020},
      {"device":"DEVICE_015", "hostname":"127.0.0.1", "port":9030}
   ]
}

server_command.json 에서 아래 정보를 읽은 후 

{  "serverCommandInfo":[
      {"command":"CMD_001", "forwardCommand":"CMD_001_A"},
      {"command":"CMD_002", "forwardCommand":"CMD_002_B"}
   ]
}

 

조합하여 아래형식으로 디바이스로 전달 한다. 

{"command":"CMD_002_B","param":"ce3c39e1"}

 

서버전송은 아래 정보를 참고한다. 

구분                                              URI
Server로부터의 Request            POST http://127.0.0.1:8010/ fromServer
Device로의 Request                   POST http://<Device hostname>:<Device port>/ fromEdge

 

그러면 아래 형식으로 response를 받게 되고, 

 Device 083 응답 : {"result":["c8d4fc55"]}

Device 015 응답 : {"result":["9604d2cd"]}

 

디바이스 별로 전달되는 것을 취합하여 아래형식으로 최종 서버에 응답한다. 

{"result":["c8d4fc55","9604d2cd"]}

 

 

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;

namespace SP_TEST
{
    class DeviceInfo
    {
        public string device = null;
        public string hostname = null;
        public int port = 0;
    }

    class Program
    {
        // Command Info 관리 리스트 
        static Dictionary<string, string> CmdInfo = new Dictionary<string, string>();
        static Dictionary<string, DeviceInfo> dicDeviceInfo = new Dictionary<string, DeviceInfo>();

        static void Main(string[] args)
        {
            //// 파일로부터 Command Info 읽어오기 
            LoadCmdInfo();
            LoadDeviceInfo();

            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://127.0.0.1:8010/");
            listener.Start();

            while (true)
            {
                var context = listener.GetContext();
                Console.WriteLine(string.Format(">>>>>>>>>>>>>>[{0}] Request({1}) : {2}", DateTime.Now.ToString("hh:mm:ss.fff"), context.Request.HttpMethod, context.Request.Url));

                Thread th = new Thread(Http_Server);
                th.Start(context);
            }
        }

        static void Http_Server(Object obj)
        {
            string strRes = null;
            HttpListenerContext context = (HttpListenerContext)obj;

            Console.WriteLine("Http_Server Thread Start : " + context.Request.RawUrl);

            StreamReader sr = new StreamReader(context.Request.InputStream);
            JObject body = JObject.Parse(sr.ReadToEnd());
            sr.Close();
            Console.WriteLine("body : " + body);

            switch (context.Request.RawUrl)
            {
                case "/fromServer":
                    strRes = sendToDevices(body["command"].ToString(), body["param"].ToString(), body["targetDevice"].ToObject<List<string>>());
                    break;
                default:
                    Console.WriteLine("error");
                    break;
            }

            if (strRes != null)
            {
                byte[] data = Encoding.UTF8.GetBytes(strRes);
                context.Response.OutputStream.Write(data, 0, data.Length);
            }
            context.Response.StatusCode = 200;
            context.Response.Close();
        }

        static string sendToDevices(string command, string param, List<string> targetDevice)
        {
            JObject jRes = new JObject();
            jRes["result"] = new JArray(); // device들로부터 전달되는 결과값들
            foreach (string deviceId in targetDevice)
            {
                string forwardCommand = CmdInfo[command];
                JObject deviceRet = sendToDevice(deviceId, forwardCommand, param);
                ((JArray)jRes["result"]).Add(deviceRet.GetValue("result").First);
            }
            return jRes.ToString();
        }

        // 특정 device에 command 전송
        static JObject sendToDevice(string device, string command, string param)
        {
            string url = string.Format("http://{0}:{1}/fromEdge", dicDeviceInfo[device].hostname, dicDeviceInfo[device].port);
            HttpClient client = new HttpClient();
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url);

            dynamic body = new JObject();
            body.command = command;
            body.param = param;
            Console.WriteLine($"Send to device : {url}, {body}");
            httpRequestMessage.Content = new StringContent(body.ToString(), Encoding.UTF8, "application/json");

            var res = client.SendAsync(httpRequestMessage).Result;
            string strRes = res.Content.ReadAsStringAsync().Result;
            Console.WriteLine($"Response : {strRes}");
            return JObject.Parse(strRes);
        }

        // 파일로부터 Command Info 사용하기 쉽게 읽어오기 
        static void LoadCmdInfo()
        {
            JObject jObj = JObject.Parse(File.ReadAllText(".\\INFO\\SERVER_COMMAND.JSON"));
            foreach (JObject cmd in jObj["serverCommandInfo"])
            {
                CmdInfo[cmd["command"].ToString()] = cmd["forwardCommand"].ToString();
            }
        }

        // 파일로부터 Device Info 사용하기 쉽게 읽어오기
        static void LoadDeviceInfo()
        {
            JObject jObj = JObject.Parse(File.ReadAllText(".\\INFO\\DEVICE.JSON"));
            foreach (JObject device in jObj["deviceInfo"])
            {
                DeviceInfo deviceInfo = device.ToObject<DeviceInfo>();
                dicDeviceInfo.Add(deviceInfo.device, deviceInfo);
            }
        }
    }
}

'프로그래밍 > C#' 카테고리의 다른 글

sample #2 .. No 1  (0) 2025.05.31
이것저것  (0) 2024.06.12
클라이언트 서버 예제 2  (0) 2024.05.14
서버 클라이언트 예제 1  (0) 2024.05.14
HTTP client  (0) 2024.05.13

+ Recent posts