Microsoft MVP성태의 닷넷 이야기
글쓴 사람
Sungwoo Park (musicbox3 at nate.com)
홈페이지
첨부 파일
 

예외 발생: 'System.Runtime.InteropServices.COMException'(mscorlib.ni.dll)
WinRT 정보: Only one usage of each socket address (protocol/network address/port) is normally permitted.

예외 발생: 'System.Runtime.InteropServices.COMException'(mscorlib.ni.dll)
WinRT 정보: An existing connection was forcibly closed by the remote host.

현재 ThreadPool을 사용해서 echo_server()를 실행 신호에 따른 GPIO를 제어하고 있습니다.

ThreadPoolTimer로 echo_client()가 1초마다 한번씩 특정 디바이스에 신호를 보내고 있는데요

작동은 되고 있습니다. 주기적으로 1초마다 신호를 보내고 있고 echo_server에서도 받는 신호에 따라서 특정 GPIO를 제어는 하고 있습니다.
근데 예외사항 관련 호출 문제 메세지가 뜨고 있습니다. 현재 에러가 뜨고 있는 부분은 체크해 보았습니다.


####으로 표시해놓은 두 곳
여기와 await socketListener.BindServiceNameAsync("15530");

여기에 await socket.ConnectAsync(serverHost, serverPort);

System.DirectoryServices.DirectoryServicesComException이 발생합니다.

각 소켓 서버 프로토콜 주소 포트는 하나만 쓸 수 있다 라는 이야기인데 일단 서버와 클라이언트 포트는 바꿔보았지만 포트를 바꾸는게 문제가 아닌지 해결은 되지 않았습니다.

쓰레드 사용을 잘못하고 있기 때문인가요? 익셉션을 어떻게 처리해야 할까요?

그리고 또 한가지 1초마다 수신을 하도록 만들어 놨는데 10초마다 한번 정도는 초가 어긋나는데요 이 경우는 그냥 시스템의 문제인가요?

public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            InitGPIO();
            IAsyncAction threadPoolWorkItem = Windows.System.Threading.ThreadPool.RunAsync((source) =>
            {
                //Perform the thread pool work item activity.
                while (true)
                {
                    //When WorkItem.Cancel is called, work items that have not started are canceled.
                    //if a work item is already running, it will run to completion uniess it supports cancellation.
                    //To support cancellatin, the work item should check IAsyncAction.Status for cancellation status
                    //and exit cleanly if it has been canceled.
                    if (source.Status == AsyncStatus.Canceled)
                    {
                        break;
                    }

                    echo_server();

                }
            }, WorkItemPriority.Normal);
            //echo_server();
            //echo_client();
            //DispatcherTimerSetup();

            TimeSpan period = TimeSpan.FromSeconds(1);

            ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(async (source) =>
            {
                await

                                //TODO: Work
                                
                                //Update the UI thread by using the UI core dispatcher.

                                Dispatcher.RunAsync(CoreDispatcherPriority.High,
                                    () =>
                                    {
                                        echo_client();

                                    //UI components can be accessed within this scope.


                                });

            }, period);
        }
        
       
        private GpioPin pin = null; //LED가 연결된 핀을 전역으로 제어하기 위해 메서드 밖에서 선언합니다.

        //우리가 사용할 GPIO를 초기화하는 메서드입니다.
        private void InitGPIO()

        {
            // 시스템의 기본 Gpio 컨트롤러를 가져옵니다.

            var gpio = GpioController.GetDefault();
            if (gpio == null) // 에러 처리 - null이면 GPIO를 사용할 수 없는 장치입니다.
            {
                pin = null;
                this.textBlock.Text = "There is no GPIO controller on this device.";
                return;
            }
            pin = gpio.OpenPin(18); //LED가 연결된 GPIO 18번 핀을 오픈합니다.

            //pin 객체는 InitGPIO() 메서드 바로 위에 전역으로 선언해 놨습니다.

            if (pin == null) //에러처리 - null이면 해당 핀 번호를 사용할 수 없습니다.
            {
                this.textBlock.Text = "There were problems initializing the GPIO pin.";
                return;
            }
            //LED 불을 끕니다.
            pin.Write(GpioPinValue.Low);
            //LED가 연결된 핀을 출력 모드로 설정합니다.
            pin.SetDriveMode(GpioPinDriveMode.Output);

            //텍스트 박스에 GPIO 사용이 완료되었다고 표기합니다.

            this.textBlock.Text = "GPIO pin initialized correctly.";
        }
       
        private async void echo_server()
        {
            
            try
            {
                //TCP 접속을 대기 시작하는 StreamSocketlistener를 만든다.
                Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener();
                //연결이 수신 될 때 호출하는 이벤트 핸들러를 연결
                socketListener.ConnectionReceived += SocketListener_ConnectionReceived;

                // String a = socketListener.BindEndpointAsync(HostName localhost, String local);
                //지정된 포트에 들어오는 TCP 접속을 대기 시작. 당신은 현재 사용하는 모든 포트를 지정할 수 있다.
                

               ####여기 에러입니다. await socketListener.BindServiceNameAsync("15530");

            }
            catch (Exception e)
            {
                //Handle exception.

            }

        }
        private async void SocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender,
    Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
        {
            //원격 클라이언트에서 읽어오기
            string a = args.Socket.Information.RemoteAddress.DisplayName.ToString();
            Stream inStream = args.Socket.InputStream.AsStreamForRead();
            StreamReader reader = new StreamReader(inStream);
            string request = await reader.ReadLineAsync();
            this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                textBox1.Text = a + " " + DateTime.Now.ToString("HH:mm:ss") + "\n";

                textBlock_Copy.Text = request;

                if (request.Equals("b"))
                {
                    textBlock2_Copy.Text = "켜짐";
                }
                else
                {
                    textBlock2_Copy.Text = "꺼짐";
                }
                //MessageDialog msgdlg = new MessageDialog("Choose a color", "How To Async #1");
                //msgdlg.Commands.Add(new UICommand("Red", null, Colors.Red));
            }).AsTask().Wait();
            if (request.Equals("b"))
            {
                pin.Write(GpioPinValue.High);
            }
            else
            {
                pin.Write(GpioPinValue.Low);
            }

            //Send the line back to the remote client.
            Stream outStream = args.Socket.OutputStream.AsStreamForWrite();
            StreamWriter writer = new StreamWriter(outStream);
            await writer.WriteLineAsync(request);
            await writer.FlushAsync();
        }

        private async void echo_client()
        {
            try
            {
                //Create the StreamSocket and establish a connection to the echo server.
                Windows.Networking.Sockets.StreamSocket socket = new Windows.Networking.Sockets.StreamSocket();
                
                //The server hostname that we will be establishing a connection to. We will be running the server and client locally,
                //so we will use localhost as the hostname.
                Windows.Networking.HostName serverHost = new Windows.Networking.HostName("192.168.10.142");

                //Every protocol typically has a standard port number. For example HTTP is typically 80, FTP is 20 and 21, etc.
                //For the echo server/client application we will use a random port 1337.
                string serverPort = "16530";
                
                ####여기 에러 입니다. await socket.ConnectAsync(serverHost, serverPort);

                //Write data to the echo server.
                Stream streamOut = socket.OutputStream.AsStreamForWrite();
                StreamWriter writer = new StreamWriter(streamOut);
                string request = DateTime.Now.ToString("HH:mm:ss");
                await writer.WriteLineAsync(request);
                await writer.FlushAsync();

                //Read data from the echo server.
                Stream streamIn = socket.InputStream.AsStreamForRead();
                StreamReader reader = new StreamReader(streamIn);
                string response = await reader.ReadLineAsync();
            }
            catch (Exception e)
            {
                //Handle exception here.
            }
        }
        private void button_Click(object sender, RoutedEventArgs e)
        {
            echo_client();
        }
     }








[최초 등록일: ]
[최종 수정일: 12/24/2015]


비밀번호

댓글 작성자
 



2015-12-25 07시15분
우선 소켓에 대한 사용 개념이 잘 서 있지 않은 것 같습니다. 간단하게 우선 윈폼이나 콘솔 응용 프로그램 형식으로 자신이 하려는 GPIO 로직을 다른 걸로 대체해서 테스트를 해보세요. 제 생각에는 박성우님이 지금 프로젝트를 진행하기 보다는 좀 더 공부가 필요한 것 같습니다.
정성태
2015-12-27 11시16분
[sungwoo park] 예 사실 소켓에 대한 개념이 아직 인게 사실입니다. 소켓부터 공부하도록 하겠습니다. 답변 감사합니다.
[guest]

... 31  32  33  34  [35]  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
4986익명5/14/201810848비주얼 스튜디오 wpf 프로젝트에서 어떻게 하면 exe파일과 실행에 필요한 파일들을 분리해서 정리해서 디렉토리로 묶을 수 있을까요? [4]
4985대구개발자5/7/20188434새로운 폴더만 "이름 없는 파일" 오류 [1]
4984안중언5/6/20189113교재 143page [1]
4983익명5/4/201818566(wpf) 다른 컴퓨터에서 사용하면 자꾸 ('CefSharp.Core.dll' 또는 여기에 종속되어 있는 파일이나 어셈블리 중 하나를 로드할 수 없습니다)라고 떠요.ㅠㅠ [5]
4982Soul...4/27/20189521MFC ActiveX 컨트롤 안에 있는 C# ActiveX 컨트롤 포인터 얻기 [4]
4981대전박4/25/20188427WPF IValueConverter 를 구현해서 StaticResource로 사용할때요 [1]
4980대전박4/23/20189579WPF OS버전 따라 Style 적용이 안되는 프로퍼티가 있을수 있나요? [2]
4979초보개발자4/18/201813718C# 프레임워크 버전이 다른 DLL끼리의 사용 [7]파일 다운로드1
4977Soul...4/17/20188876WebBrowser 컨트롤 Script 통신 문제 [3]
4976맹가이버4/14/20189741윈도우 서비스 프로그램에서 응용프로그램 호출하는 법 [1]
4975lemo...4/11/201810537안녕하세요 네이버로그인관련 질문드립니다. [2]
4973홍길동4/6/20188642ebook 출간 계획은 없으신가요? [2]
4978홍길동4/17/20188406    답변글 [답변]: ebook 출간 계획은 없으신가요?
4972dwkim4/3/20189623EasyHook 관련 질문 [4]
4968최홍준3/30/20188362Windows 7 Credential Provider Android와 연동 [1]
4967이대희3/30/20189475비주얼 스튜디오 설치 워크로드 중에 ".NET Core 플랫폼 간 개발" 이건 뭐하는 것인지요. [1]
4965이대희3/30/20188819자마린 설치후 안드로이드 프로젝트 생성시 디자이너가 없다는 에러가 발생합니다. [3]
4969이대희3/31/20189176    답변글 [답변]: 자마린 설치후 안드로이드 프로젝트 생성시 디자이너가 없다는 에러가 발생합니다.파일 다운로드2
4970이대희4/1/20188970        답변글 [답변]: [답변]: 자마린 설치후 안드로이드 프로젝트 생성시 디자이너가 없다는 에러가 발생합니다. [1]
4963이대희3/29/20189504UWP 스터디를 위해 찰스페졸드 저자의 Programming Windows 6판은 어떠한지요? [1]
4962포플러3/26/20189730C# 응용프로그램 (Winform)에서 unhandledexception 발생시 프로그램이 죽는 현상 이외에 재부팅될 수도 있을까요? [2]
4966포플러3/30/20189393    답변글 [답변]: C# 응용프로그램 (Winform)에서 unhandledexception 발생시 프로그램이 죽는 현상 이외에 재부팅될 수도 있을까요? [1]
4961김민욱3/26/201810333레이더 뷰어의 구현 방법(이미지 확대 축소 관련) [2]
4960hurd...3/18/20189999OCX 관련한 질문을 드리고자 합니다. [1]
4959익명3/10/20189038교재 199page 델리게이트와 object를 이용한 범용 정렬 코드 [1]
4957멍멍이2/13/20189629System.Console - WriteLine함수의 제너릭 사용 [1]
... 31  32  33  34  [35]  36  37  38  39  40  41  42  43  44  45  ...