ClientSimpleTcp 클래스

생성자

Connect

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

namespace csharp_test_client
{
    public class ClientSimpleTcp
    {
		    // 소켓 만들면 쓸 변수 선언
        public Socket Sock = null;  
        // 최근 에러 메시지 뭔지 알기 위한 용도? 
        public string LatestErrorMsg;
        

        //소켓연결        
        public bool Connect(string ip, int port)
        {
            try
            {
		            // IP 주소 객체 생성 -> ip를 매개변수로 받아서 Parse
                IPAddress serverIP = IPAddress.Parse(ip);
                // 포트번호 변수 할당
                int serverPort = port;

								// 소켓 생성(TCP)
                Sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                // 위에서 설정한 값으로 EndPoint 만들고 거기에 만든 소켓 연결
                Sock.Connect(new IPEndPoint(serverIP, serverPort));

								// 소켓이 안만들어졌거나 연결이 안됐으면 return
                if (Sock == null || Sock.Connected == false)
                {
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
		            // 에러 발생 시 에러 메시지
                LatestErrorMsg = ex.Message;
                return false;
            }
        }

Receive

// Recv
public Tuple<int,byte[]> Receive()
{
    try
    {
		    // 데이터 받을 바이트배열(버퍼) 생성
        byte[] ReadBuffer = new byte[2048];
        // 소켓에서 데이터 받아오기 (받을곳, 여기부터, 이만큼, 소켓 작업의 특성)
        var nRecv = Sock.Receive(ReadBuffer, 0, ReadBuffer.Length, SocketFlags.None);

				// 수신된 데이터 크기가 0이면 받은게 없음
        if (nRecv == 0)
        {
            return null;
        }

				// 받은 데이터 크기, 받은 내용 으로 튜플 만들어서 반환
        return Tuple.Create(nRecv,ReadBuffer);
    }
    catch (SocketException se)
    {
        LatestErrorMsg = se.Message;
    }

    return null;
}

Send

//스트림에 쓰기
public void Send(byte[] sendData)
{
   try
   {
			  // 소켓이 있고, 연결된 상태일때
        if (Sock != null && Sock.Connected) //연결상태 유무 확인
        {
		        // 데이터 전송
            Sock.Send(sendData, 0, sendData.Length, SocketFlags.None);
        }
        else
        {
            LatestErrorMsg = "먼저 채팅서버에 접속하세요!";
        }
    }
    catch (SocketException se)
    {
        LatestErrorMsg = se.Message;
    }
}

Close

//소켓과 스트림 닫기
public void Close()
{
	 // 소켓이 있고, 연결 상태일 때
   if (Sock != null && Sock.Connected)
   {
      //Sock.Shutdown(SocketShutdown.Both);
        Sock.Close();
    }
}

IsConnected

public bool IsConnected() 
{ 
		if (Sock != null && Sock.Connected)
		{
			return true;
		}
	
		return false;
}