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

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를 몇 번 하는지 확인해 보세요. ^^
정성태

... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
55358/5/20216788안녕하세요. 초보 웹 개발자입니다. [10]파일 다운로드2
5534하영7/28/20215296clrprofiler 를 사용하여 세션정보 접근 [6]파일 다운로드1
5533함준혁7/20/20214792.net fpspread 관련 질문입니다.. [1]
5532조윤상7/15/20216158바인딩은 성공 했습니다. 그런데 브라우저에서 인증서가 없다고 나옵니다. [2]
5530ocm7/14/20215777pthread_create [7]파일 다운로드1
5529ksc7/13/20214939Source Generator 관련 질문이 있습니다. [1]
5528초심으로7/9/20216136MDI 에서 USB 연결해제 알림이 안되는 문제 질문 드려봅니다. [7]파일 다운로드1
5527wuny7/7/20215016제어관련 고민을하다가 소캣방식 선택 [2]
5526이성열 donator7/7/20216596wpf x64로 만든 메인 프로그램에서 dll로 된 UserControl 속성이 디자인타임에 잘 안보이는 문제 [10]파일 다운로드2
5525Wuny7/7/20217159제가 만든 배포파일은 window에서 막는걸까요? [2]파일 다운로드1
5524하이스컬7/2/20216467특정 이벤트에서 다른 이벤트 호출 관련 문의 [3]
5523민우7/1/202112204도커 사용시 윈도우 이미지 생성도 가능한가요? [2]
5522질문6/28/20216904WPF에서 splash screen이 나타나는 위치를 변경할 수 있나요? [3]
5521김민혁6/24/20217013.exe 파일 에러에 관한 질문 입니다. [3]
5520한예지 donator6/21/20216783랜덤함수 질문있습니다!! [2]
5519리얼킴6/19/20215720.net framwork 4.0 에서 4.8로 꼭 가야할까요?? [1]
5518한예지 donator6/18/20216439ArrayList, IList에 대해 질문 있습니다. [3]
5517wunsy6/18/20216874winform에서 Button 활성화, 비활성화 [4]
5516ocm6/15/20215878mips 어셈블리 연산 다시 질문드려요 (첨부파일 갱신됨) [2]파일 다운로드1
5515ocm6/14/20216762mips 어셈블리 연산 [6]파일 다운로드1
5514jongs6/11/20217480GethashCode와 String대한 질문 [2]
5513labe...6/11/20217210C# Winform 에서 Label에 동일한 Color를 넣었을 때 처리방법이 궁금합니다. [2]
55126/11/20217986xlwings 가 실행조차 되지 않습니다. ㅠㅠ [7]
5511Syong6/9/20216796User Control에 string array 속성 추가하는 방법 [4]
5510jay6/8/20215812string 문자열에 쌍따옴표(")를 넣고 싶습니다. [1]파일 다운로드1
5509한예지 donator6/3/20215763ExeccuteNonQuery 질문있습니다! [2]
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...