Microsoft MVP성태의 닷넷 이야기
글쓴 사람
Sungwoo Park (musicbox3 at nate.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

라즈베리파이 GPIO를 컨트롤 하는 프로그램을 작성했더니 신호에 따라 컨트롤은 잘 되었습니다.
하지만 받은 값을 textBox에 전달하려 하는데 잘 안됩니다.
namespace echo_Server
 {

    /// <summary>
     /// </summary>
     public sealed partial class MainPage : Page
     {
         
         public MainPage()
         {
             
             this.InitializeComponent();
             acho_sever();
             achoclient();
            
         }
         private async void acho_sever()
         {
             try
             {
                 //Create a StreamSocketListener to start listening for TCP connections.
                 Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener();

                //Hook up an event handler to call when connections are received.
                 socketListener.ConnectionReceived += SocketListener_ConnectionReceived;

                //Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
                 await socketListener.BindServiceNameAsync("1337");
                 
             }
             catch (Exception e)
             {
                 //Handle exception.
                 
             }

        }
         private async void SocketListener_ConnectionReceived(Windows.Networking.Sockets.StreamSocketListener sender,
     Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args)
         {
             //Read line from the remote client.
             Stream inStream = args.Socket.InputStream.AsStreamForRead();
             StreamReader reader = new StreamReader(inStream);
             string request = await reader.ReadLineAsync();
            //try //일단 익셉션처리를 해보았습니다. 익셉션 에러는 안났는데요
            //{
            // textBox.Text = request; //여기도
            //}
            //catch (COMException)
            //{
            // textBox.Text = request; //또 여기에 넣어봐도 텍스트 박스가 반응을 안합니다.
            //}
            //Send the line back to the remote client.
             Stream outStream = args.Socket.OutputStream.AsStreamForWrite();
             StreamWriter writer = new StreamWriter(outStream);
//리턴값으로 돌려서 값을 반환하고 싶지만 void라 할 수 ㅇ없었습니다. 이런저런 시도를 해봤지만 실패했습니다.
어떻게 해서 출력하면 좋을까요?

            await writer.WriteLineAsync(request);
            await writer.FlushAsync();
         }


[연관 글]






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


비밀번호

댓글 작성자
 



2015-12-07 12시13분
예외가 발생하지 않았다면 실제로 request에는 빈 문자열이 있을 가능성이 있습니다. 확인해 보셨나요? ReadLineAsync 한번만 호출했으니 가장 처음의 라인을 가져왔다는 것이고 그것이 개행만 포함된 빈 문자열일 수 있습니다. (디버그 모드로 실행해서 request 변수에 들어간 내용을 확인해 보세요.)
정성태
2015-12-07 08시11분
[박성우] 답변 감사합니다. 제가 실제로 이 소스로 GPIO를 제어했습니다.
Stream inStream = args.Socket.InputStream.AsStreamForRead();
            StreamReader reader = new StreamReader(inStream);
            string request = await reader.ReadLineAsync();
            try
            {
                test = request;
            }
            catch (COMException) {}
            // 이 부분을 추가해서 확인해 보았습니다. 클라이언트로 b를 입력해서 보내니까 제가 미리 선언해 놓은 pin번호 LED에 불이 들어왔으며 b를 제외한 다른 문자열을 넣으니까 불이 꺼졌습니다.
            if (request.Equals("b"))
            {
                pin.Write(GpioPinValue.High);
            }
            else
            {
                pin.Write(GpioPinValue.Low);
            }
그 부분에서 빈 문자열이 아닌 것은 확신 할 수 있습니다. 어떻게 할지 모르겠어서 겟터와 셋터를 만들어서도 사용해보려 했는데 뭔가 SocketListener_ConnectionReceived 이 클래스 안에만 들어가면 다른곳에서 선언된 것들은 사용하려 할때마다 예외 상황이 뜨거나 global::System.Diagnostics.Debugger.Break();여기가 노랗게 되네요.
[guest]
2015-12-07 08시23분
[박성우] try {textBox.Text = request;}
catch (COMException){textBox.Text = request;}
일단 request에는 값이 들어오는 것은 확인 되었습니다. 하지만 text박스에 아무런 변화가 없는 것으로 봐서 try catch는 무시 되고 있는 것 같습니다.
[guest]
2015-12-07 02시09분
다음부터는 ^^ 예외가 발생하는 코드는 다음과 같이 해서 메시지를 출력해 보세요.

try
{
} catch (Exception e)
{
  System.Diagnostics.Debug.WriteLine(e.ToString());
}

그럼, Output 창에서 다음과 같은 메시지를 볼 수 있고,

System.Exception: The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
   at Windows.UI.Xaml.Controls.TextBox.put_Text(String value)
   at App1.MainPage.<SocketListener_ConnectionReceived>d__2.MoveNext()

이 메시지를 올려주셨다면 좀더 쉽게 답변을 드릴 수 있었을 것입니다. 답은 다음의 글을 참고하세요. ^^

The application called an interface that was marshalled for a different thread in window 8
; http://stackoverflow.com/questions/11218911/the-application-called-an-interface-that-was-marshalled-for-a-different-thread-i
정성태
2015-12-08 12시35분
예 말씀해주신대로 참고해서 작성해 넣었더니 잘 됩니다. 감사합니다. 앞으로는 예외 메세지를 같이 출력해서 확인해보겠습니다. 정말 감사합니다.
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                textBox.Text = request;
            }).AsTask().Wait();
Sungwoo Park

... 76  77  78  [79]  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
494안연준10/25/20068086    답변글 [답변]: 스마트클라이언트 배포에서 Config 내용이 이해가 안되요 [2]
489안연준10/23/20069067스마트 클라이언트 배포시 문제점
491안연준10/24/20069548    답변글 [답변]: 스마트 클라이언트 배포시 문제점 [2]
492안연준10/24/20068780        답변글 [답변]: [답변]: 스마트 클라이언트 배포시 문제점
488안연준10/23/20068527닷넷 프레임워크 때문에 일어난 어의없는 상황 [2]
484서민균10/20/20068557스마트 클라이언트 인쇄질문 올린 사람입니다.
486정성태10/22/20069831    답변글 [답변]: 스마트 클라이언트 인쇄질문 올린 사람입니다.
483guest10/19/20068805asp.net 에서 Com+ 등록된 dll 의 차이점이 무엇인지요?
485정성태10/22/20069259    답변글 [답변]: asp.net 에서 Com+ 등록된 dll 의 차이점이 무엇인지요?
490deve...10/23/200612146        답변글 [답변]: [답변]: asp.net 에서 Com+ 등록된 dll 의 차이점이 무엇인지요? [1]
478서민균10/17/200610132스마트 클라이언트로 만든 컴포넌트가 인쇄가 안되요.....ㅜㅜ [5]
477sagi...10/15/20069773bho 와 mfc 메시지 전송 관련 질문입니다.
479정성태10/17/200611570    답변글 [답변]: bho 와 mfc 메시지 전송 관련 질문입니다.
480sagi...10/17/20069553        답변글 [답변]: 감사합니다. [1]
481sagi...10/19/20069382            답변글 [답변]: 죄송합니다 .. 한가지 더 여쭤 볼께요
482정성태10/19/20069047                답변글 [답변]: [답변]: 죄송합니다 .. 한가지 더 여쭤 볼께요
496sagi...10/27/20069713                    답변글 [답변]: 감사드립니다.
476문태정10/11/200611845FarPointSpread로 출력 시 시트 암호설정문제 [1]
474임경훈10/9/200612759세션값이 유지가 안되는데요? [1]
470쿠리마9/29/20069080고수님들께 질문 올립니다. (C# COM Server에서 C++ Client에게 string맴버 포함한 구조체 배열 넘기기)파일 다운로드1
473정성태10/5/200611068    답변글 [답변]: 고수님들께 질문 올립니다. (C# COM Server에서 C++ Client에게 string맴버 포함한 구조체 배열 넘기기) [3]파일 다운로드1
469이방은9/29/20068424질문이 있어요.. [2]
466이승기9/25/20068504Attribute를 이용한 COM 구현 시 interface의 상속 [1]
467이승기9/27/20068090    답변글 [답변]: Attribute를 이용한 COM 구현 시 interface의 상속
4659/23/20067723vb.net에서 c에서 보내는 Post메쎄지를 잡아서 처리할수 없을가요? [1]
464정윤수9/22/20069432asp.net 에서 DataSet 을 RecordSet 으로 변환 [2]
... 76  77  78  [79]  80  81  82  83  84  85  86  87  88  89  90  ...