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

+ Recent posts