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

계속 시도 해 보았는데요. async에 await 대해 공부하고 어떤 방식으로 작용하는지 또 왜 써야 하는지는 알겠습니다.

그런데 어떻게 써야 할지 또 어디에서 어떤 메소드에 적용해야 할지 모르겠습니다.

신호를 주기적으로 보내다가 신호를 받을때 잠시 멈춰 신호를 받고 다시 신호를 보내고 싶은데 잘 안되네요.

현재 제가 작업한 소스입니다. 근데 생각한대로 안돼고 있습니다.

어디다가 async await를 적용해야 할까요? 또 async await를 어떻게 공부하면 좋을지도 모르겠습니다. 책도 보고 구글링도 해보지만 아무래도 어렵습니다.

namespace L_Server
{

    public sealed partial class MainPage : Page
    {
        
         public MainPage()
        {
            this.InitializeComponent();
            echo_server();
            DispatcherTimerSetup();
        }
              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("1337");
            }
            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;
            }).AsTask().Wait();
         
            //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 = "1337";
                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();
        }
       
        DispatcherTimer dispatcherTimer;

        public void DispatcherTimerSetup()
        {
            dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            dispatcherTimer.Start();
            TimerLog.Text += "dispatcherTimer.IsEnabled = " + dispatcherTimer.IsEnabled + "\n";
        }

        void dispatcherTimer_Tick(object sender, object e)
        {
            echo_client();
        }
    }
}








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


비밀번호

댓글 작성자
 



2015-12-21 12시21분
async/await을 어디에/어떤 메서드에 적용할지 혼동이 되신다면 간단하게 윈폼이나 콘솔 응용 프로그램으로 실습해 보세요. 그것을 이해하기 위해 UWP앱을 만드는 것은 오히려 혼란만 가중시킬 수 있습니다.

그리고 UWP앱은 기존의 I/O 메서드들이 blocking을 유발하므로 그 부분에 있어서는 거의 모두 비동기로 대체되었습니다. 따라서, I/O에 관해서는 (소켓을 포함해서) 사용하고 있는 것 자체가 async/await을 유발하도록 디자인되어 있으므로 적용 여부를 굳이 판단하실 필요가 없습니다.
정성태
2015-12-21 12시35분
[sungwoo park] 예 답변 감사합니다. 이해하기 위해 UWP앱을 만드는 것은 아닙니다.
지금 프로젝트가 Windows 10 Iot운영체제로 잡혔는데 이 이 운영체제는 UWP앱만 지원해서요 UWP앱으로 작업을 하고 있습니다.
그래서 UWP 앱으로 작업하고 있었는데 아무래도 원폼이나 콘솔 응용프로그램 먼저 실습해보고 이해 해야겠네요.
사실 xaml과 프로그램이 분리되어 있기도 하여서 지금 많이 어렵게 느껴집니다.
신기하게 다른언어들도 특히 비슷한 느낌이 많은 자바를 다뤄 보았는데 C# async/await는 참 어렵네요.
[guest]
2015-12-21 01시28분
혹시 근처에 대형 서점이 있어 제 책을 보실 수 있다면 6.6 스레딩과 10.2 비동기 호출 부분을 읽어보시면 도움이 되지 않을까 싶군요. ^^
정성태
2015-12-21 01시46분
예 감사합니다. 구입해서 공부해보겠습니다.
Sungwoo Park
2015-12-21 01시47분
아 책은 제가 구입했었습니다. 한번 보고 공부해 보겠습니다.
Sungwoo Park

... 31  32  33  34  35  36  37  38  39  40  41  42  [43]  44  45  ...
NoWriterDateCnt.TitleFile(s)
4772자연인10/27/201614418hwpctrl을 사용하는 사이트에서 나와 브라우저를 종료하면 오류메세지가 나옵니다. [1]파일 다운로드1
4771문종훈10/18/201614459.net 소스 질문이 있습니다 [2]
4770누구게~...10/15/201611689세도나 [1]
4769spow...10/13/201610511올리시는 게시물에 '좋아요'를 선택할 수 있도록 해주세요 [3]
4768브라운10/11/201612250질문 하나만 드려도 될까요 [4]
4767암호군10/4/201616615c# aes 128 암복호화 관련 문의드립니다. [3]
4766김신철9/29/201611472Visual Studio 2015에서 .net 3.5로 c# 6.0 사용시 문제점에 대해서 궁금합니다. [1]
4765spow...9/23/201610893참조를 통해 속성의 값을 변경하고 싶을 때 우아한 코딩 방법이 있을까요? [2]
4764지현명9/22/201612439Visual Studio 2008 c#에서 추가된 솔류션의 디버깅이 안걸립니다. [2]파일 다운로드1
4763송기태9/20/201611209안녕하세요! 질문이 있어 문의드립니다! [1]파일 다운로드1
4762김신철9/20/201612339Visual Studio 2015 마이그레이션 후 빌드 및 에러 문제.. 도와주세요~ [2]
4761JH9/19/201612751WPF로 Viewbox 사용 시 폰트 크기 일정화 여부 [1]
4760초보9/18/201612689유닉스서버(HP)에서 C# 서버 프로그램 실행 가능 한지요? [1]
4759dev009/16/201613488Queue out of memory [3]
4758임기성9/12/201613062MS오피스 워드 64비트에서 32비트 COM개체 사용방법 문의 [2]
4757조영준9/7/201611098DLL 후킹과 관련해서 질문이 있습니다. [2]
4756Kim ...9/6/201613152drag&drop 관련해서 문의 드립니다. [6]
4755stel...9/4/201611997안녕하세요! 윈도우 창에 관련되서 질문입니다.! [3]
4754초보개발자8/25/201610886UWP 의 적용 범위에 대해서 어떻게 생각하십니까? [1]
4753조호찬8/23/201615760sybase 의 한글 가져오기 문의 [7]
4752타미플루8/19/201611375IIS 로그에서 time-taken이 0이 나올수 있나요? [4]
4751김민석8/16/201611567가변크기의 구조체를 SendMessage로 타 프로세스에 전송하는 방법이 있을까요? [1]
4750강준8/13/201613101ElementHost Memory Leak 현상 (아래내용과 동일 첨부 추가^^) [5]파일 다운로드1
4749강준8/11/201612115ElementHost Memory Leak 현상 [6]
4748Bere...8/3/201610972그냥 생각이 들어서 여기 글 써봅니다. [1]
4746힘찬도약8/2/201611235[asp.net] local에서 cookies값이 읽혀지지 않는 경우 [1]
... 31  32  33  34  35  36  37  38  39  40  41  42  [43]  44  45  ...