[c#] C# 직렬화와 네트워크 통신
C#에서 직렬화와 네트워크 통신을 사용하여 데이터를 전송하는 방법에 대해 알아보겠습니다.
직렬화(Serialization)
직렬화는 객체를 데이터 스트림으로 변환하는 과정을 말합니다. C#에서는 System.Runtime.Serialization
네임스페이스를 사용하여 직렬화 기능을 제공합니다.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class SerializationExample
{
public byte[] SerializeObject<T>(T obj)
{
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
formatter.Serialize(stream, obj);
return stream.ToArray();
}
}
public T DeserializeObject<T>(byte[] data)
{
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream(data))
{
return (T)formatter.Deserialize(stream);
}
}
}
위의 예제는 Person
클래스를 직렬화하고 역직렬화하는 방법을 보여줍니다.
네트워크 통신(Network Communication)
C#에서는 System.Net.Sockets
네임스페이스를 사용하여 소켓을 통한 네트워크 통신을 제공합니다.
using System;
using System.Net;
using System.Net.Sockets;
public class Server
{
public static void Main()
{
byte[] bytes = new byte[1024];
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
Socket handler = listener.Accept();
int bytesRec = handler.Receive(bytes);
Console.WriteLine("Received : {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
public class Client
{
public static void Main()
{
byte[] bytes = new byte[1024];
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
Socket sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
byte[] msg = Encoding.ASCII.GetBytes("Hello from client!");
int bytesSent = sender.Send(msg);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
}
위의 예제는 C#을 사용하여 간단한 클라이언트-서버 모델을 구현하는 방법을 보여줍니다.
C#에서는 직렬화와 소켓을 이용하여 객체를 데이터로 변환하고 네트워크를 통해 전송할 수 있습니다.
이렇게 직렬화와 네트워크 통신을 활용하여 데이터를 안정적으로 전송할 수 있습니다.
참고 자료
- C# Serialization: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/
- C# Socket Programming: https://docs.microsoft.com/en-us/dotnet/framework/network-programming/socket-code-examples