#클라이언트 사이드
- 유니티 5.3버전 JsonUtility 사용
#서버 사이드
- boost/property_tree/json_parser 사용
#유니티 클라이언트 코드
프로토콜 정의
1 2 3 4 5 6 7 8 9 10 11 12 | namespace Protocols { namespace Json { [Serializable] public class ReqLogin { public string id; public string pw; } } } | cs |
송신 부분
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class LoginSceneInput : MonoBehaviour { public InputField idField; // id 입력 필드 public InputField pwField; // pw 입력 필드 // 버튼이 눌렸을 때 호출되는 함수 public void TryLogin() { // id와 pw 필드에서 텍스트를 가져옴 var id = idField.text; var pw = pwField.text; // 패킷의 id와 pw 값 설정 var packet = new Protocols.Json.ReqLogin(); packet.id = id; packet.pw = pw; // 구조체를 json 포맷으로 변환 var packetJson = JsonUtility.ToJson(packet); try { // 서버로 송신 var arr = System.Text.Encoding.UTF8.GetBytes(packetJson.ToCharArray()); NetworkSession.Instance.SendPacket(arr, arr.Length); } catch (Exception e) { Debug.Log(e.Message); return; } } } | cs |
# c++ 서버 코드
수신 부분
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | virtual void received(receive_buffer& buf) override { using ptree = boost::property_tree::ptree; namespace json = boost::property_tree::json_parser; boost::asio::streambuf sb; sb.sputn(buf.data<char*>(), buf.size()); std::istream is{ &sb }; // json을 읽는다. ptree pt; json::read_json(is, pt); auto idval = pt.get<std::string>("id"); // id 필드에서 값을 가져옴 auto pwval = pt.get<std::string>("pw"); // pw 필드에서 값을 가져옴 } | cs |
json 파일 읽는거 첨 해보면서 정리했는데 혹시 필요한 사람 있을까봐 올림~! 즐거운 하루
댓글 0