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

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

... 46  47  48  49  50  51  52  [53]  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
1536솔솔3/9/201519950mac address얻으려고 하는데요.. [1]
1535Stud...3/4/201520074C#엔 MFC의 theApp 과 같은 기능을 하는것이 없나요? [3]
1534김동진3/4/201519859C#에서 BHO로 Windows Explorer에서의 동작이 가능할지요 [2]
1533김동현3/3/201520099컴파일 된 프로그램에 코드 삽입(?) 관련입니다. [1]
1532반가워요3/3/201523335C# 소켓연결에 packet송수신... [8]
1531강현수3/2/201522513C# com 등록 시 GUID 변경 관련 문의 [1]
1529김민규2/15/201520908C++ 64bit/32bit [3]파일 다운로드1
1528김개똥2/14/201518297좀 관련없는 질문이지만, 정말 답답하고 찾는데 명확한 해답 찾지못해 질문 올립니다. <Windows 사용자 인증> [1]
1527방문자1/27/201520138System Timer의 Tick에서 Backgroundworker를 호출하면 스레드 문제가 있을까요? [1]
1526황상대1/26/201522075C# 마샬링 관련 질문이 있습니다. [1]
1525Ji-y...1/19/201521781시작하세요 C# 프로그래밍 도서에 관한 질문입니다. [1]
1523임종복12/31/201429928windows 2008 r2에서 ms-sql 2008 서버사용시 tls문제점 [3]
1524임종복1/4/201524341    답변글 [답변]: windows 2008 r2에서 ms-sql 2008 서버사용시 tls문제점 [2]
1521윤대욱12/19/201420492C++ 에서 서버와 클라이언트를 나누어서 구조체 전달에 대해서 궁금합니다. [1]파일 다운로드1
152012/10/201421355datetime관련해서요 [1]
1516aTo12/1/201420126wpf 배포관련. [3]
1514얄미운제리11/17/201420311[C# Mono]Mono Chart 개발 문의드립니다. [1]
1355미나리나물11/13/201417843RDP 접속 방식 질문드리고 싶습니다. [1]
1353송용국11/10/201417045TeamFoundationServer 에 소스를 Target서버로 옮기는(내려주는) 방법 있나요? [1]
1351blue...11/7/201422650c# webbrowser 모바일환경 접속 [1]
1350에메11/7/201422577WCF namedpipe 퍼블리싱 충돌 문제 [3]파일 다운로드1
1349Chun...11/6/201426355Microsoft. Net Framework 액세스 거부 오류...... [2]
1348김준석11/6/201422754 Mini dump 기록 안되는 현상 [2]파일 다운로드1
1346개미11/5/201437155https페이지에서 http서버에 있는 이미지 파일 호출시 보안 오류 [8]
1345장구니11/4/201421445AWS 인스턴스를 만들었는데 [1]
1343h11/2/201420883안녕하세요 [1]
... 46  47  48  49  50  51  52  [53]  54  55  56  57  58  59  60  ...