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

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)
5644ㅇㅇ4/6/20224253c# 프로그램을 이용하여 리눅스상에 파일 생성이 가능한가요? [1]
5643유필재4/5/20224129TCP클라이언트 연결 및 통신관련하여 문의드려요 [1]
5642차가워4/4/20224386UdpClient 패킷 수신 문의 [4]
5641장성욱4/4/20224781코어 할당 및 cpu 부하테스트 질문 [7]
5640icoo...4/4/20224308웹가든에서 메모리 동적 업데이트 방법 [1]
5639차가워4/4/20224227c++ 서버 c# 클라이언트 호환 문의 [1]
5638초급4/3/20224534c# sql server 연동 [1]
5637따봉이4/1/20224799Winform Form Load 후 자동 캡쳐관련 [1]파일 다운로드1
5636김철순3/31/20224764WPF에서 Richtext의 View 문의 [5]
5635guest3/30/20224758안정적인 pinning이 가능하네요. [3]파일 다운로드1
5633꿀주세요3/30/20224378선생님 마우스 클릭이벤트 질문이 있습니다. [4]
5632김현수3/30/20224754Remote Desktop으로 접속시 WPF UI 가 다시 그려지는 이벤트를 막을 수 없을까요? [3]
5631김기헌3/24/20224361WPF 컨트롤의 그래픽 처리관련 질문드립니다 [2]파일 다운로드1
5630장성욱3/24/20224174로깅관련 질문입니다. [2]
5629감사합니...3/23/20224414함수에서 예외가 발생하면 try ~ catch처리기를 찾을 때 까지 상위 함수로 계속 올라가나요? [2]
5628홍길동3/23/20225069질문드립니다. [2]파일 다운로드1
5626연준혁3/21/20224316안녕하세요. [3]
5625jaew...3/18/20225262c# 8.0 도서를 구입한 사람입니다. [1]
5624초보자3/17/20224224람다 캡처 관련 문의 [2]
5623한예지 donator3/15/20224633인터프리터 원리가 궁금합니다. [4]
5622김민아3/8/20224540const와 readonly의 명확한 차이가 이게 맞나요? [2]
5621장성욱3/8/20224316c# 로그 관련 질문 [1]
5620김민아3/7/20224353안녕하세요 비관리 객체를 반환하는 메소드 호출 시 궁금한 점이 있어서 질문드립니다 [2]
5619팡팡이3/3/20225712RSA 문의드립니다. [3]
5618김기헌3/2/20224218안녕하세요 생성자 옆에 this 키워드를 붙여 생성자를 여러 개 호출 시 질문드립니다 [2]
5617Edun2/25/20224345ArgumentOutOrRangeException에러 발생 [2]파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...