You are on page 1of 53

제 18 장 : 웹서비스

ASP.NET - 웹 서비스
• 웹 서비스의 특징
• 웹 서비스 작성
• Visual Studio.NET 을 이용한 웹 서비스 작성
• 웹 서비스 호출
• Visual Studio.NET 을 이용한 웹 서비스 호출
•인터넷을 통한 어플리케이션 간의 통신
• XML 기반으로 하는 분산 컴포넌트
–브라우저를 통한 호출
–프락시를 이용한 호출
•프로그래밍 언어에 독립적
•프로토콜 중립적
•플랫폼 독립적
•무상태 구조

브라우즈 뿐만 아니라 모든 클라이언트에서 데이터를 받을 수 있다 .


웹 서비스 작성 (1)

•WebService 지시어 추가하기

<%@
<%@WebService
WebServiceLanguage=“C#”
Language=“C#”Class=“MyClass”
Class=“MyClass”%>
%>

•네임 스페이스 포함

using
usingSystem;
System;
using
usingSystem.Web.Services;
System.Web.Services;
웹 서비스 작성 (2)

웹 메쏘드를 포함한 클래스 작성

public
publicclass
classMyClass
MyClass{{
[WebMethod]
[WebMethod]
public
publicstring
stringPrice()
Price(){{
return
return“W100”;
“W100”;
}}
}}

•확장자 .asmx 로 저장
–하나의 .asmx 파일에는 하나의 서비스 제공 클래스만 제공할 수 있

isual Studio.NET 을 이용한 웹 서비스 작성

1. 프로젝트
1. 프로젝트 생성
생성
isual Studio.NET 을 이용한 웹 서비스 작성

Service1.asmx.cx
Service1.asmx.cx
ing System;
ing System.Collections;
ing System.ComponentModel;
ing System.Data;
ing System.Diagnostics;
ing System.Web;
ing System.Web.Services;

mespace SvcTest1

/// <summary>
/// Summary description for Service1.
/// </summary>
public class Calculate : System.Web.Services.WebService
{
public Calculate()
{
//CODEGEN: This call is required by the ASP.NET Web Services Designer
InitializeComponent();
}

[WebMethod]
public int Add(int i, int j)
{
return i+j;
}
}
isual Studio.NET 을 이용한 웹 서비스 작성

프로그램
프로그램 실행
실행
isual Studio.NET 을 이용한 웹 서비스 작성

서비스
서비스 설명
설명 실행
실행 ((서비스를
서비스를 기술하는 XML 파일
기술하는 XML 파일))
isual Studio.NET 을 이용한 웹 서비스 작성

Add 실행
Add 실행

XML 방식의 실행 결과
isual Studio.NET 을 이용하지 않는 웹 서비스 호출

•브라우저를 이용한 웹 서비스 호출

•프락시를 통한 웹 서비스 호출
–프락시 코드 생성

wsdl
wsdl/language:cs
/language:cs/namespace:MyNamespace
/namespace:MyNamespace
http://localhost/Service1.asmx?wsdl
http://localhost/Service1.asmx?wsdl

- 프락시 코드 컴파일

csc
csc/t:library
/t:library/r:System.XML.dll
/r:System.XML.dll/r:System.Web.Services.dll
/r:System.Web.Services.dll
/r:System.Web.dll
/r:System.Web.dllService1.cs
Service1.cs

–일반적인 컴포넌트 처럼 호출
isual Studio.NET 을 이용한 웹 서비스 호출

•윈도우 어플리케이션 형태의 클라이언트


•WebReference 추가
•Show All Files 로 생성된 프록시 확인
isual Studio.NET 을 이용한 웹 서비스 호출

1. 프로젝트
1. 프로젝트 추가
추가
isual Studio.NET 을 이용한 웹 서비스 호출

2. 컨트롤
2. 컨트롤 추가
추가
isual Studio.NET 을 이용한 웹 서비스 호출

3.
3. Web Reference 추가
Web Reference 추가

http://localhost/test2/SvcTest1/Service1.asmx
isual Studio.NET 을 이용한 웹 서비스 호출

4.
4. Web Reference 추가된
Web Reference 추가된 후의
후의 솔루션
솔루션 탐색기
탐색기
isual Studio.NET 을 이용한 웹 서비스 호출

5. 폼에서
5. Button1 이벤트
폼에서 Button1 이벤트 등록
등록

rivate void button1_Click(object sender, System.EventArgs e)

localhost.Calculate calc = new localhost.Calculate();


MessageBox.Show(calc.Add(Int32.Parse(textBox1.Text),
Int32.Parse(textBox2.Text)).ToString());
isual Studio.NET 을 이용한 웹 서비스 호출

Localhost 존재
Localhost 존재 유무
유무 확인
확인

웹 참조의 Service1.wsdl 을 클릭한 다음 , “ 모든 파일 보기”


아이콘인 4 번째 아이콘을 클릭하면 , Service1.cs 파일이
보인다 .

이 파일의 코드를 보면 네임스페이스가


localhost 임을 확인할 수 있다 .
isual Studio.NET 을 이용한 웹 서비스 호출

5. 서비스
5. 서비스 내의 Add 바디
내의 Add 바디 변경
변경 후
후 실행
실행

namespace SvcTest1
{

[WebMethod]
public int Add(int i, int j)
{
return i-j;
}

}

서비스만 컴파일 하여도 클라이언트는 정상 동작

그러나 , Add 의 프로파일을 바꿀 경우 , 클라이언트



비정상적인 동작을 하며 , 이때는 클라이언트도 다시
컴파일하여 , 프로파일을 서버와 맞추어 주어야 한다
.
ASP.NET – WebService DISCO, Session, Application 사용하

•WebService Discovery 란 ?
•WebService Discovery 의 종류
•Dynamic WebService Discovery 작성
•Manual WebService Discovery 작성
•WebService Discovery 를 이용한 서비스 검색
•WebService 에서 Application/Session 객체 이용
ebService Discovery 란 ?

•해당 웹 어플리케이션에서 제공하고 있는 WebService 에 대한 정보 검색 (WSDL)


서비스
•DISCO
–WebService Discovery 정보 추출을 위한 파일
•WSDL 란 ?
–WebServices Description Language
–XML 형식으로 WebService 에 대한 정보 기술
–추출 방법

http://severname/application_name/service1.asmx?wsdl
http://severname/application_name/service1.asmx?wsdl
ynamic WebService Discovery 작성

•Dynamic DISCO 파일 작성
–Visual Sutdio.NET ASP.NET Web Application 의 확장자 .vsdisco
파일
•Dynamic DISCO 파일의 예

<?xml
<?xmlversion="1.0"
version="1.0"?>
?>
<dynamicDiscovery
<dynamicDiscoveryxmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
<exclude
<excludepath="_vti_cnf"
path="_vti_cnf"/>/>
<exclude
<excludepath="_vti_pvt"
path="_vti_pvt"/>/>
<exclude
<excludepath="_vti_log"
path="_vti_log"/>/>
<exclude
<exclude path="_vti_script"/>
path="_vti_script" />
<exclude path="_vti_txt" />
<exclude path="_vti_txt" />
<exclude
<excludepath="Web
path="WebReferences"
References"/>
/>
</dynamicDiscovery>
</dynamicDiscovery>

dynamic 자동으로 웹 서비스하는 정보를 뽑아오라


exclude 이 서비시에 한행서는 정보를 가져오지 마라
ynamic WebService Discovery 작성

1. 웹서비스
1. 웹서비스 프로젝트
프로젝트 만들기
만들기
ynamic WebService Discovery 작성

2. Service1.asmx.cs 코드
2. Service1.asmx.cs 코드 수정
수정
ng System;
ng System.Collections;
ng System.ComponentModel;
ng System.Data;
ng System.Diagnostics;
ng System.Web;
ng System.Web.Services;

espace SvcTest3

/// <summary>
/// Summary description for Service1.
/// </summary>
public class Calculate : System.Web.Services.WebService
{
public Calculate()
{
//CODEGEN: This call is required by the ASP.NET Web Services Designer
InitializeComponent();
}


private void InitializeComponent()
{
}


protected override void Dispose( bool disposing )
{
}
ynamic WebService Discovery 작성

2. Service1.asmx.cs 코드
2. Service1.asmx.cs 코드 수정
수정

[WebMethod]
public Point Add(Point x, Point y)
{
return x + y;
}

public class Point


{
public int x;
public int y;
public static Point operator+(Point l, Point r)
{
return new Point(l.x + r.x, l.y+r.y);

public Point()
{
x=y=0;
}

public Point(int x, int y)


{
this.x = x; this.y = y;
}
}
}
}
ynamic WebService Discovery 작성

3. Service2 추가
3. Service2 추가
ynamic WebService Discovery 작성

4. Service2.asmx.cs 코드
4. Service2.asmx.cs 코드 수정
수정

ng System;
ng System.Collections;
ng System.ComponentModel;
ng System.Data;
ng System.Diagnostics;
ng System.Web;
ng System.Web.Services;

espace SvcTest3

/// <summary>
/// Summary description for Service2.
/// </summary>
public class Sum : System.Web.Services.WebService
{
public Sum()
{
//CODEGEN: This call is required by the ASP.NET Web Services Designer
InitializeComponent();
}

[WebMethod]
public int AutoSum(int num)
{
return num + 100;
}
}
ynamic WebService Discovery 작성

5. vsdisco 파일
5. vsdisco 파일

ml version="1.0" ?>
namicDiscovery xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
clude path="_vti_cnf" />
clude path="_vti_pvt" />
clude path="_vti_log" />
clude path="_vti_script" />
clude path="_vti_txt" />
clude path="Web References" />
ynamicDiscovery>
ynamic WebService Discovery 작성

6. 클라이언트용
6. 클라이언트용 윈도우
윈도우 폼
폼 추가
추가
ynamic WebService Discovery 작성

7. Reference 추가
7. Reference 추가
Svctest3 가 제공하는 모든 서비스가 나타난다 .

http://localhost/test2/svctest3/svctest3.vsdisco
ynamic WebService Discovery 작성

8. 추가된
8. 추가된 Web
Web Reference
Reference

SvcTest3 에서 제공되는 서비스가 웹 레퍼런스로 참조되고 있다 .


ynamic WebService Discovery 작성

9. WinForm에
9. WinForm 에 버튼
버튼 추가
추가 및
및 코드
코드 삽입
삽입

private void button1_Click(object sender, System.EventArgs e)


{
localhost.Calculate calc = new localhost.Calculate();
localhost.Point p1 = new localhost.Point();

p1.x = 3; p1.y = 5;

localhost.Point p2 = new localhost.Point();


p2.x = 1; p2.y = 13;

localhost.Point result = calc.Add(p1,p2);


MessageBox.Show(result.x.ToString() + "/" +
result.y.ToString());
}
ynamic WebService Discovery 작성

10. 실행한
10. 실행한 모습
모습
anual WebService Discovery 작성

•Static DISCO 파일 작성
–.disco 확장자
•Static DISCO 파일의 예

<?xml
<?xmlversion="1.0"
version="1.0"encoding="utf-8"?>
encoding="utf-8"?>
<discovery
<discoveryxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://schemas.xmlsoap.org/disco/">
xmlns="http://schemas.xmlsoap.org/disco/">
<contractRef
<contractRefref="http://localhost/lecture_48/Service1.asmx?wsdl"
ref="http://localhost/lecture_48/Service1.asmx?wsdl"
docRef="http://localhost/lecture_48/Service1.asmx"
docRef="http://localhost/lecture_48/Service1.asmx"
xmlns="http://schemas.xmlsoap.org/disco/scl/"
xmlns="http://schemas.xmlsoap.org/disco/scl/"/> />
<contractRef
<contractRefref="http://localhost/lecture_48/Service2.asmx?wsdl"
ref="http://localhost/lecture_48/Service2.asmx?wsdl"
docRef="http://localhost/lecture_48_webservice/Service2.asmx"
docRef="http://localhost/lecture_48_webservice/Service2.asmx"
xmlns="http://schemas.xmlsoap.org/disco/scl/"
xmlns="http://schemas.xmlsoap.org/disco/scl/"/> />
</discovery>
</discovery>
ebService Discovery 를 이용한 서비스 검색

•Disco.exe 를 이용한 서비스 검색

•VS.NET 의 Web Reference 를 이용한 서비스 검색


–데모
bService 에서 Application/Session 객체 이용

•Application 객체 이용
–일반 ASP.NET 의 어플리케이션 객체와 사용법동일
–Application[“key”]
•Session 객체 이용 가능
–객체 별로 Session 객체 이용 가능
–각 클라이언트 어플리케이션은 필요한 쿠기 정보를 메모리 상에 저장
–Session[“key”]

[WebMethod(EnableSession=true)]
[WebMethod(EnableSession=true)]
public
publicint
intSessionTest()
SessionTest()
{{
if(Session["key"]
if(Session["key"]====null)
null) {{Session["key"]
Session["key"]==0;0;}}
int
intinc
inc==(int)
(int)Session["key"];
Session["key"];
Session["key"]
Session["key"]==++inc;
++inc;
return
returninc;
inc;
}}
bService 에서 Application/Session 객체 이용

웹 서비스 프로젝트를 생성

프로젝트 명 : SvcTest4

Service1.asmx.cs 파일을 아래와 같이 수정 .

public class Service1 : System.Web.Services.WebService


{

[WebMethod(EnableSession=true)]
public int SessionTest()
{
if(Session["key"] == null)
{
Session["key"] = 0;
}

int inc = (int) Session["key"];


Session["key"] = ++inc;

return inc;
}
}

프로젝트 실행
앞에서 배운 세션 객체와 동일하게 실행되는 것을 확인할 수 있다 .
bService 에서 Application/Session 객체 이용

실행한
실행한 모습
모습
ASP.NET – WebService 비동기 프로그래밍 모델
•비동기 프로그래밍 모델이란 ?
•비동기 프로그래밍 디자인 패턴
•WebService 비동기 호출을 위한 프락시 생성
•WebService 비동기 프로그래밍 시 인자의 의미
•WebService 비동기 프로그래밍 실행 모델
•비동기 프로그래밍 실습
비동기 프로그래밍 모델이란 ?

•메쏘드 호출의 두 가지 방식
–동기 호출
•블럭킹 모델
–비 동기 호출
•비 블럭킹 모델

•.NET 비동기 프로그래밍 모델 적용 예


–File IO
–Networking
–Remoting Service
–ASP.NET WebService
–Message Queue
–Async Delegate
1. 웹
1. 웹 서비스
서비스 프로젝트
프로젝트 생성
생성

Sevice1.asmx.cs 에 다음의 코드를 추가


[WebMethod]
[WebMethod]
public
public int
int AsyncTest(int
AsyncTest(int p1,
p1, out
out int
int p2,
p2, ref
ref int
int p3)
p3)
{{
p2
p2 == p3
p3 == p1;
p1;
System.Threading.Thread.Sleep(7000);
System.Threading.Thread.Sleep(7000);
return p1;
return p1;
}}
2. 클라이언트
2. 클라이언트 프로젝트
프로젝트 추가
추가(WinForm)
(WinForm)
3. 웹
3. 웹 참조
참조
4. 윈폼에
4. 윈폼에 아래의
아래의 코드
코드 추가
추가
public class Form1 : System.Windows.Forms.Form
{

localhost.Service1 svc = new localhost.Service1();
private void button1_Click(object sender, System.EventArgs e)
{
int ref_i = 0;
svc.BeginAsyncTest(1, ref_i, new AsyncCallback(CallMe)," 이연미 ");
}

private void CallMe(IAsyncResult ar)


{
int ref_i = 0;
int out_i = 0;
svc.EndAsyncTest(ar, out ref_i, out out_i);
string str = (string) ar.AsyncState;
MessageBox.Show(
String.Format("{0}/{1}/{2}",
str,out_i,ref_i));
}

private void button2_Click(object sender, System.EventArgs e)


{
int ref_i = 0;
int out_i = 0;
int result = svc.AsyncTest(1,ref ref_i,out out_i);
MessageBox.Show(
String.Format("{0}/{1}/{2}",
result,out_i,ref_i));
}
}
5. 실행된
5. 실행된 모습
모습

웹 참조내에서 Service1.cs 파일
참조내에서 Service1.cs 파일((내용
내용 설명
설명))
ace WinThread1.localhost {

[System.Diagnostics.DebuggerStepThroughAttribute()]
public System.IAsyncResult BeginAsyncTest(int p1, int p3, System.AsyncCallback callback, object asy
return this.BeginInvoke("AsyncTest", new object[] {
p1,
p3}, callback, asyncState);
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
public int EndAsyncTest(System.IAsyncResult asyncResult, out int p3, out int p2) {
object[] results = this.EndInvoke(asyncResult);
p3 = ((int)(results[1]));
p2 = ((int)(results[2]));
return ((int)(results[0]));
}
•BeginInvoke(), EndInvoke() 이용

•비동기 메쏘드 호출 작성 순서
1.BeginInvoke() or BeginMethod() 메쏘드의 인자로 콜백 위임 형
(delegate) 등록

2.Call-Back 위임 형 (delegate) 내의 EndInvoke() or EndMethod() 메쏘


드 호출로
실행 결과 판단
WebService 비동기 호출을 위한 프락시 생성

•WebService 의 WebMethod 구현 시 추가적으로 BeginMethod(),


EndMethod() 자동 생성
•예
–ASP.NET WebService WebMethod

public
publicint
intAsyncTest(int
AsyncTest(intp1,
p1,out
outint
intp2,
p2,ref
refint
intp3)
p3)

–생성되어진 Proxy 의 메쏘드


•동기 호출을 위한 메쏘드

public
publicint
intAsyncTest(int
AsyncTest(intp1,
p1,out
outint
intp2,
p2,ref
refint
intp3)
p3)

•비 동기 호출을 위한 메쏘드
System.IAsyncResult
System.IAsyncResultBeginAsyncTest(int
BeginAsyncTest(intp1,
p1,int
intp3,
p3,
System.AsyncCallback
System.AsyncCallbackcallback,
callback,object
objectasyncState)
asyncState)
int
intEndAsyncTest(System.IAsyncResult
EndAsyncTest(System.IAsyncResultasyncResult,
asyncResult,out
outint
intp3,
p3,out
outint
intp2)
p2)
WebService 비동기 프로그래밍 시 인자의 의미

•BeginMethod() 의 인자

System.IAsyncResult
System.IAsyncResultBeginAsyncTest(int
BeginAsyncTest(intp1,
p1,int
intp3,
p3,
System.AsyncCallback
System.AsyncCallbackcallback,
callback,object
objectasyncState)
asyncState)
–input 인자 , ref 인자 : 모두 input 인자
–callback : 메쏘드 호출이 끝나면 호출 해야 할 위임형
–asyncstate : 콜백 메쏘드로 넘겨줄 인자

•EndMethod() 의 인자

int
intEndAsyncTest(System.IAsyncResult
EndAsyncTest(System.IAsyncResultasyncResult,
asyncResult,out
outint
intp3,
p3,out
outint
intp2)
p2)

–반환 값 int : 원형 메쏘드의 반환값


–asyncResult : 비동기 메쏘드 호출에 대한 결과
–ref 인자 , out 인자 : 모두 out 인자
WebService 비동기 프로그래밍 실행 모델

비동기 프로그래밍 실행 모델

locahost.Service1
locahost.Service1svc
svc
==new
newlocalhost.Service1();
localhost.Service1();
……
private 윈도우 메시지 처리 쓰레드
privatevoid
voidButton_Click
Button_Click
(object
(objectsend,
send,EventArgs
EventArgse)e){{
……
svc.BeginAsyncTest
svc.BeginAsyncTest
(…,new 실제
실제웹웹서비스
서비스서버는
서버는
(…,newAsyncCallback(CallMe),..);
AsyncCallback(CallMe),..); 비동기
}} 비동기/ /동기
동기
… 호출여부
호출여부관여하지
관여하지않음
않음

……
private
privatevoid
voidCallMe(IAsyncResult
CallMe(IAsyncResultar)
ar)
{{
}}
실제 웹 서비스 서버와
통신 쓰레드

You might also like