소켓 통신은 네트워크 프로그래밍을 통해 클라이언트와 서버 간의 데이터 교환을 가능하게 합니다.
기본 구조
- 서버 (Server):
- 서버는 클라이언트의 연결을 기다리며, 클라이언트와 연결되면 데이터를 주고받습니다.
- 클라이언트 (Client):
- 클라이언트는 서버에 연결을 요청하며, 연결이 성립되면 데이터를 주고받습니다.
기본 클래스
- Socket: 소켓을 생성하고 제어하는 클래스.
- TcpListener: TCP 서버 소켓을 쉽게 만들기 위한 클래스.
- TcpClient: TCP 클라이언트 소켓을 쉽게 만들기 위한 클래스.
- NetworkStream: 소켓에서 데이터 전송을 위해 사용하는 스트림.
서버 예제
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Server
{
static void Main()
{
TcpListener server = null;
try
{
int port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
byte[] bytes = new byte[256];
string data = null;
while (true)
{
Console.WriteLine("Waiting for a connection...");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.UTF8.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
byte[] msg = Encoding.UTF8.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
server.Stop();
}
Console.WriteLine("Server stopped.");
}
}
서버:
- TcpListener 객체를 사용하여 서버를 초기화하고 특정 포트에서 클라이언트 연결을 대기합니다.
- 클라이언트가 연결되면 NetworkStream을 통해 데이터를 읽고 UTF-8로 디코딩합니다.
- 데이터를 주고받는 동안 UTF-8로 인코딩 및 디코딩합니다.
- 클라이언트 연결이 종료되면 소켓을 닫습니다.
클라이언트 예제
using System;
using System.Net.Sockets;
using System.Text;
class Client
{
static void Main()
{
try
{
int port = 13000;
TcpClient client = new TcpClient("127.0.0.1", port);
NetworkStream stream = client.GetStream();
string message = "Hello, World! 안녕하세요!";
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
data = new byte[256];
string responseData = string.Empty;
int bytes = stream.Read(data, 0, data.Length);
responseData = Encoding.UTF8.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("Client closed.");
}
}
클라이언트:
- TcpClient 객체를 사용하여 서버에 연결합니다.
- NetworkStream을 통해 서버에 데이터를 UTF-8로 인코딩하여 보냅니다.
- 서버로부터의 응답을 UTF-8로 디코딩하여 출력합니다.
- 통신이 종료되면 스트림과 클라이언트를 닫습니다.
'공부 > C#' 카테고리의 다른 글
C# Packet Generator (0) | 2024.06.13 |
---|---|
BitConverter란? (1) | 2024.06.12 |
패킷(Packet) (0) | 2024.06.10 |
Session 이란? (0) | 2024.06.10 |
TCP / UDP (0) | 2024.06.10 |