Microsoft MVP성태의 닷넷 이야기
TCP 소켓 [링크 복사], [링크+제목 복사]
조회: 7519
글쓴 사람
안중언
홈페이지
첨부 파일

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

namespace TCP_Test_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("현재 클라이언트 컴퓨터의 IP : " + Utility.GetCurrentIPAddress());

            // 클라이언트 소켓이 동작하는 스레드.
            Thread clientThread = new Thread(ClientFunction);
            clientThread.IsBackground = true;
            clientThread.Start();

            Console.WriteLine("현재 클라이언트 프로그램 실행중입니다. (종료하려면 아무 키나 누르세요...)");
            Console.ReadLine();
        }

        private static void ClientFunction(object obj)
        {
            Console.WriteLine("현재 클라이언트 프로그램을 시작하겠습니다.");

            using (Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                EndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("220.119.20.225"), 11200);

                clientSocket.Connect(serverEndPoint);

                int nTimes = 5;

                while (nTimes-- > 0)
                {
                    // 클라이언트 -> 서버 : 데이터 송신.
                    byte[] buf = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
                    Console.WriteLine(DateTime.Now.ToString());
                    clientSocket.Send(buf);

                    // 서버 -> 클라이언트 : 데이터 수신.
                    byte[] receivebytes = new byte[1024];
                    int nReceive = clientSocket.Receive(receivebytes);
                    string txt = Encoding.UTF8.GetString(receivebytes, 0, nReceive);

                    Console.WriteLine(txt);

                    Thread.Sleep(1000);
                }
            }

            Console.WriteLine("TCP Client socket : Closed");
        }
    }
}

public static class Utility
{
    public static IPAddress GetCurrentIPAddress()
    {
        IPAddress[] iPAddresses = Dns.GetHostEntry(Dns.GetHostName()).AddressList;

        foreach (IPAddress iPAddress in iPAddresses)
        {
            if (iPAddress.AddressFamily == AddressFamily.InterNetwork)
            {
                return iPAddress;
            }
        }
        return null;
    }
}

서버측은 488 Page 그대로 구현했습니다.

책 488 Page 내용에 UDP에서는 5번 보냈길래 TCP 에서도 5번 보내니까 이런 오류가 뜨는데 이건 왜 이런건가요?








[최초 등록일: ]
[최종 수정일: 11/10/2018]


비밀번호

댓글 작성자
 



2018-11-10 11시44분
서버 측의 코드가 Send / Receive를 몇 번 하는지 확인해 보세요. ^^
정성태

1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
5828김재영2/19/20233146장기적으로는 this 구문을 안쓰는게 맞을까요? [2]
5827lee2/18/20233061파이썬 설치 오류 질문입니다 [1]
5826Syong2/14/20233644Socket 관련 Leak (OverlappedAsyncResult, OverlappedData) 관련 문의 [7]파일 다운로드1
5825박성원2/14/20233214Listview 컨트롤의 화면 전환 시 갱신 속도 [1]
5823검은콩2/13/20233814catch(Exception ex)의 line번호를 쉽게 알 수 없는지요? [7]
5822김지우2/11/20233088책을 보면서 sync, async 이해가 되지 않는 부분이 있습니다. [5]파일 다운로드2
5821검은콩2/9/20233114Async 신뢰성과 소켓데이터 [4]
5820차가워2/8/20233175다른 프로세스 실행 후 포커스 가져오기 [3]
5819취준생2/7/20233329WPF 관련 실무가 궁금합니다. [3]
5818윤길2/7/20232777ObservableCollection 에서 INotifyPropertyChanged 구현해야하나요? [2]
5817흰털너부리2/7/20232916배포 시 winform 실행 콘솔로그 보는 방법 [1]
5816흰털너부리2/6/20232727.net core json array validation 질문 드립니다. [1]
5815김재영2/6/20232850종단간 암호화에 대해 시나리오인데 타당한 시나리오일까요? [2]
5814한예지 donator2/6/20233184decompile? [9]
5813김재영2/5/20233079openssl genrsa 2048시 키 생성이 다르게 됩니다. - 파일첨부 [4]파일 다운로드1
5812김재영2/5/20233358openssl genrsa 2048시 키 생성이 다르게 됩니다. [2]
5811치르바2/3/20233188MiniDumpWriteDump API로 덤프수집을 했는데요.. [3]
5810이건우1/31/20233290윈도우서비스를 통한 웹통신관련 질문입니다 [3]
5809이상훈1/31/20233731다채널 영상 디스플레이어 개발 관련 질문입니다. [3]
5808근우1/30/20233409WPF 에서 UserControl 과 ControlTemplate 의 차이점은 무엇인가요? [6]
5807궁금맨1/28/20234567C# 10 책에 나온 예제의 결과가 제 컴에서는 좀 달라서요. 이유가 궁금합니다. [1]
5806스레드1/25/20233078총정리 - 다양한 스레드들 [초안] [1]파일 다운로드1
5805어웨이트1/25/20232940Taskcontinuewith vs Async/Await [2]파일 다운로드1
5804나이많은...1/25/20232801MS의 Dependency Injection(DI)에 AddSingleton으로 등록된 객체의 Event 등록후 사용시 앱 종료시 별도로 Event를 해지해야 하나요? [2]
5803dssc...1/24/20233030드라이브 문자를 통해서 물리 디스크 명칭을 알아내고 싶습니다. [1]
5802모바일앱1/22/20232921XAMARINE vs Android Studio [7]
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...