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

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)
5766김명훈12/9/202212899웹브라우저에서 묻지 않고 바로 다운로드 [2]
5765hong12/1/202213257Winform(.Net6) 클라이언트에서 SignalR Core 웹서버에 접속시 인증서 문제 [3]파일 다운로드1
5764요한11/30/202213383c++ 동일한 객체인지 비교 방법문의 [2]
5763고필석11/30/202212694시작하자마자 비정상 종료하는 프로세스에 대한 문제 해결 조언 요청 드립니다. [3]
5762흰털너부리11/30/202212664wpf mvvm ui update 로딩중 표시 [1]
5761민성11/29/202212653죄송하지만 한가지만 더 여쭈어 보겠습니다 [1]
5760민성11/29/202213180안녕하세요 [2]
5759문정환11/28/202213162c# socket 통신할때 빅엔디언으로 바꿔줘야 하나요? [1]
5758라떼11/28/202216322Linux 에서 winform UI 어플리케이션 실행하기 [3]
5757흰털너부리11/25/202214741asp.net core EF AddDbContext,AddDbContextFactory 차이점 알려주세요 [1]
5756흰털너부리11/25/202214813asp.net core web api에서 json 특정 property 무시하는 방법 문의 드립니다. System.Text.Json 사용중입니다. [1]
5755문정환11/24/202215201싱글스레드 프로그램도 컨텍스트 스위칭이 생길 수 있나요? [4]
5754초급11/24/202215125c# 소켓통신 [1]
5753흰털너부리11/24/202213898List와 ObservableCollection을 비교 해서 다른 값 추출 FirstOrDefault 객체 비교 [4]파일 다운로드1
5752푸헐11/15/202213027app.config 에 connectionStrings를 aspnet_regiis로 enctyption [4]
5751차가워11/8/202215688vs2022 preview net7 AOT 콘솔 실행 성능 [7]
5749차가워11/4/202213546전처리 지시문 #if DEBUG 배포시 실행 여부 [1]
5748김기헌11/3/202215239안녕하세요 선생님 싱글톤 패턴을 꼭 이렇게 사용해야 하나요? [6]
5747김기헌11/2/202213750안녕하세요 선생님 네트워크 관련 용어 중 IP 주소가 왜 논리적 주소라고 표현되는 건가요? [2]
5746물냉면이...11/2/202213842서로 다른 클래스에 있는 동일 함수의 일괄 호출 방법에 대해 궁금합니다. [3]
5745흰털너부리11/1/202213489.net core web api 사용 제한에 관한 질문 입니다. [2]
5744차가워10/31/202215955윈폼 Console.WriteLine(); 연산 문의 [1]
5743흰털너부리10/27/202213983reflection, static, override 질문입니다. [1]
5742차가워10/27/202212656하나의 socket에 여러 스레드가 접근 하는 경우 [1]
5741조호상10/27/202213227OpenCVSharp4 구현 가능 문의 [1]
5740혜성10/26/202215737Visual Studio 2022 C# 콘솔 프로그램 기본 코드 변경된 이유는 무엇인가요? [2]
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...