개발자이야기/C#

C# 소켓통신의 기본

퐈니스타일 2023. 6. 22. 10:15

C#에서 소켓 통신을 하기 위해서는 System.Net.Sockets 네임스페이스를 사용해야 합니다. 

1. 서버 구현하기
서버를 구현하기 위해서는 TcpListener 클래스를 사용합니다. TcpListener 클래스는 클라이언트의 연결 요청을 받아들이고, 클라이언트와 통신할 수 있는 소켓을 생성합니다.

 

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class Server
{
    static void Main(string[] args)
    {
        TcpListener server = null;
        try
        {
            // 서버 IP 주소와 포트 번호 설정
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            int port = 10007;

            // TcpListener 객체 생성
            server = new TcpListener(ipAddress, port);

            // 서버 시작
            server.Start();

            // 클라이언트 연결 대기
            Console.WriteLine("서버 시작. 클라이언트 연결 대기 중...");

            while (true)
            {
                // 클라이언트 연결 요청 수락
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("클라이언트 연결됨.");

                // 클라이언트와 통신할 NetworkStream 객체 생성
                NetworkStream stream = client.GetStream();

                // 클라이언트로부터 데이터 수신
                byte[] buffer = new byte[1024];
                int bytes = stream.Read(buffer, 0, buffer.Length);
                string data = Encoding.UTF8.GetString(buffer, 0, bytes);
                Console.WriteLine("수신한 데이터: {0}", data);

                // 클라이언트에게 데이터 송신
                byte[] msg = Encoding.UTF8.GetBytes("서버에서 보낸 메시지: " + data);
                stream.Write(msg, 0, msg.Length);

                // 클라이언트와 연결 종료
                client.Close();
                Console.WriteLine("클라이언트와 연결 종료.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("예외 발생: {0}", e);
        }
        finally
        {
            // 서버 종료
            server.Stop();
            Console.WriteLine("서버 종료.");
        }
    }
}

 


2. 클라이언트 구현하기
클라이언트를 구현하기 위해서는 TcpClient 클래스를 사용합니다. TcpClient 클래스는 서버에 연결하고, 서버와 통신할 수 있는 소켓을 생성합니다.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class Client
{
    static void Main(string[] args)
    {
        TcpClient client = null;
        try
        {
            // 서버 IP 주소와 포트 번호 설정
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            int port = 13000;

            // TcpClient 객체 생성
            client = new TcpClient();

            // 서버에 연결
            client.Connect(ipAddress, port);
            Console.WriteLine("서버에 연결됨.");

            // 서버로 데이터 송신
            string data = "안녕하세요.";
            byte[] msg = Encoding.UTF8.GetBytes(data);
            NetworkStream stream = client.GetStream();
            stream.Write(msg, 0, msg.Length);
            Console.WriteLine("송신한 데이터: {0}", data);

            // 서버로부터 데이터 수신
            byte[] buffer = new byte[1024];
            int bytes = stream.Read(buffer, 0, buffer.Length);
            data = Encoding.UTF8.GetString(buffer, 0, bytes);
            Console.WriteLine("수신한 데이터: {0}", data);

            // 서버와 연결 종료
            client.Close();
            Console.WriteLine("서버와 연결 종료.");
        }
        catch (Exception e)
        {
            Console.WriteLine("예외 발생: {0}", e);
        }
    }
}
728x90
반응형