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

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)
5894송부장4/14/202314644[질문] Visual Studio 2022에서 '도구 상자 항목 선택'의 'COM 구성 요소' 탭에서 ActiveX 목록이 보이지 않습니다. [3]파일 다운로드2
5893감사합니...4/14/202312302오라클 OLEDB방식 접속 후 SELECT 'TEST' TEST_VALUE FROM DUAL의 값이 이상합니다. [1]
5892한무4/14/202312161C# 으로 백그라운드에서 워드를 실행하여 매크로 실행이 가능 할까요? [2]
5891리세4/14/202313619안녕하세요.C# 서버프로그램에서의 Mysql 쿼리문제(다중쿼리 실행)에 대해 문의드립니다. [2]
5890guest4/14/202314668C# 프리랜서로 돈 벌려면 성태님 책 마스터하면 되나요? [6]
5889전예찬4/14/202312299C# 파일 복사 관련 질문 드립니다. [3]
5888정경구4/12/202312438C# 첫 환경 세팅과 관련해서 [4]
5887HAN4/12/202312490안녕하세요 파이썬도 공유 가능 할까요? [1]
5886guest4/11/202314692필요한 어셈블리만 다운로드 및 재로딩하는 방법에 관하여 [2]
5885guest4/11/202312489c#으로 드림위버같은 거 만들어볼려는데요 [6]
5884궁금이4/11/202312995부모 클래스에서 예외 발생시 힙 영역에 할당 ? [2]
5883코딩초짜4/9/20231254410c언어 usleep 에 대해서 요 [2]
5882조은현4/7/202311959선생님 안녕하세요! wpf의 성능 개선에 대해서 질문드려요! [1]파일 다운로드1
5881guest4/6/202313035static method - <에러메시지 Extension method must be defined in a non-generic static class> [4]
5880유비4/4/202311962WPF DataGrid CollectionView, IEditableCollectionView 관련 문의 [1]
5879guest4/4/202313915Async method의 에러 표시 [3]
5878guest4/3/202314383C#으로 CMOS 설정 변경가능한지요? [4]
5875guest4/2/202314567성태님 책을 완독 하고 Static [7]
5874민성4/1/202312977안녕하세요 질문 하나만 드릴깨요~ [1]
5873guest3/31/202314645제어판에서 삭제불가 MS Edge ---> 레지스트리 편집기에서도 안보임 [6]파일 다운로드1
58723/31/202313776web config 파일 확인부탁드려요 [6]
58713/31/202312949web config 파일 수정이요 [2]파일 다운로드1
5870guest3/30/202312687.NET Core SDK 삭제 시 주의 사항 [4]파일 다운로드1
5869guest3/30/202313321Dictionary의 Update 그리고 Foreach [7]
5868guest3/29/202312486Speech Recognition과 Form1 그리고 정확도 [4]파일 다운로드1
5866월급쟁이3/28/202312269cmake 크로스 컴파일 관련하여 질문이 있습니다 [1]
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...