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

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)
5778이건우12/30/20224508안녕하세요 c#에서 dll참조 관련 질문드립니다. [4]
5777감사합니...12/29/20223530UI Thread에 Invoke 처리관련 궁금합니다. [3]
5776pdf맨12/28/20223334C# MouseUp Event + pdf [10]
5775민성12/28/20223102안녕하세요 Class 관련해서 예외처리를 하나로 받아낼수 있는 방법 [1]
5774중급12/27/20223884중급개발자란 어느 수준인지요? [4]
5773김영식12/26/20223425c# 압축파일 읽어 올 때 BinaryRead 한글 처리 문제 [1]
5772눈송이12/26/20223540Excel VSTO 는 왜 Net Core, Net 5, 6 버전을 사용하지 않나요? [2]
5771김훈12/26/20223643c# .net client application 망분리(내부망,외부망) 환경에서 의문의 외부사이트 호출 대기 [2]
5770lsh12/26/20223247클라우디움안에 있는 파일을 File.Copy 하고싶은데 코드로는 접근을 못하나요? [1]
5769울타리12/20/20223305Active Directory 2012R2 2016 또는 2019 마이그렝션 문의 드립니다. [1]
5768c++12/14/20224060Thread를 사용한 C++ DLL에 관련된 질문입니다. [6]파일 다운로드2
5767민성12/9/20223414안녕하세요 ashx로 화일을 저장하고 화일명을 리턴하는데요 [1]
5766김명훈12/9/20223566웹브라우저에서 묻지 않고 바로 다운로드 [2]
5765hong12/1/20223785Winform(.Net6) 클라이언트에서 SignalR Core 웹서버에 접속시 인증서 문제 [3]파일 다운로드1
5764요한11/30/20224012c++ 동일한 객체인지 비교 방법문의 [2]
5763고필석11/30/20223511시작하자마자 비정상 종료하는 프로세스에 대한 문제 해결 조언 요청 드립니다. [3]
5762흰털너부리11/30/20223500wpf mvvm ui update 로딩중 표시 [1]
5761민성11/29/20223402죄송하지만 한가지만 더 여쭈어 보겠습니다 [1]
5760민성11/29/20223341안녕하세요 [2]
5759문정환11/28/20223683c# socket 통신할때 빅엔디언으로 바꿔줘야 하나요? [1]
5758라떼11/28/20224879Linux 에서 winform UI 어플리케이션 실행하기 [3]
5757흰털너부리11/25/20223824asp.net core EF AddDbContext,AddDbContextFactory 차이점 알려주세요 [1]
5756흰털너부리11/25/20223403asp.net core web api에서 json 특정 property 무시하는 방법 문의 드립니다. System.Text.Json 사용중입니다. [1]
5755문정환11/24/20223743싱글스레드 프로그램도 컨텍스트 스위칭이 생길 수 있나요? [4]
5754초급11/24/20223581c# 소켓통신 [1]
5753흰털너부리11/24/20223386List와 ObservableCollection을 비교 해서 다른 값 추출 FirstOrDefault 객체 비교 [4]파일 다운로드1
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...