본문 바로가기

네트워크

[TCP/IP 소켓 프로그래밍] TCP 서버

TCP Server

 

닷넷 프레임워크에서 TCP 서버를 개발하기 위해서는 System.Net.Sockets.TcpListener 클래스가 필요하며, 내부적으로 System.Net.Sockets.Socket 클래스의 기능을 사용해서 TCP Port Listening 기능을 구현한다. Tcp 서버는 TcpListener 클래스의 기능을 이용해서 포트를 열어두고, 클라이언트 측의 접속을 대기하고 있다가, 요청이 들어오면 이를 받아들여서 TcpClient 객체를 생성할 수 있으며 이 TcpClient 객체를 이용해서 NetworkStream 을 통해 클라이언트 측과 통신 할 수 있게 된다. 

 

TcpListener 사용법

 

using System.Net.Sockets;
using System.Net;
 
namespace TcpSrv
{
    class Program
    {
        static void Main(string[] args)
        {
            // (1) 로컬 포트 7000 을 Listen
            TcpListener listener = new TcpListener(IPAddress.Any, 7000);
            listener.Start();
 
            byte[] buff = new byte[1024];
 
            while (true)
            {
                // (2) TcpClient Connection 요청을 받아들여
                //     서버에서 새 TcpClient 객체를 생성하여 리턴
                TcpClient tc = listener.AcceptTcpClient();
 
                // (3) TcpClient 객체에서 NetworkStream을 얻어옴 
                NetworkStream stream = tc.GetStream();
 
                // (4) 클라이언트가 연결을 끊을 때까지 데이타 수신
                int nbytes;
                while ((nbytes = stream.Read(buff, 0, buff.Length)) > 0)
                {
                    // (5) 데이타 그대로 송신
                    stream.Write(buff, 0, nbytes);
                }
                 
                // (6) 스트림과 TcpClient 객체 
                stream.Close();
                tc.Close();
 
                // (7) 계속 반복
            }
        }
    }
}