2011-12-17 2 views
5

나머지 서버와 클라이언트를 만들어야합니다.나머지가있는 java 서버 만들기

나는 소켓을 사용하는 tutorial을 우연히 발견했습니다. 클라이언트가 실제로 다른 언어로 존재하기 때문에 REST 호출, 아마도 HTTP를 사용할 수 있기를 원합니다.

Socket api 대신 java.net.*에서 무엇을 사용해야합니까? 소켓 API를 사용하면 C++ 및 PHP를 사용하여이 서버와 통신 할 수 있습니까? 또는 REST와 함께해야합니까?

모든 방향이 좋습니다.

+1

[REST] (http://en.wikipedia.org/wiki/REST)는 HTTP의 컨텍스트에서 실제로 만 의미가 있습니다. 원시 소켓을 통해 직접 실행되는 자체 작성 API를 사용하여 REST 뒤에 _principles_을 확실히 사용할 수 있지만 그 시점에서는 REST가 아닐 수 있습니다. – sarnold

+0

잘 HTTP를 통해 통신 할 수 싶습니다. 어떤 API를 사용할 지 잘 모르겠습니다. 가능하면 사용자 지정 포트에서. – DarthVader

답변

6

휴식 서비스를 만드는 데 사용할 수있는 많은 것들이 있습니다. 그런 다음 거의 모든 것이 소비 될 수 있습니다. 특정 awesomeness의 능력은 귀하의 웹 브라우저에서 그들을 공격하는 것입니다, 왜냐하면 우리 모두가 그들에게 익숙하기 때문입니다.

'빠르고 더러운'휴식 솔루션이 필요한 경우 Restlet을 사용합니다. 유일한 해결책이라고 주장하지는 않겠지 만 지금까지 사용해 본 것이 가장 쉽습니다. 저는 회의에서 "나는 XYZ를 10 분 안에 올릴 수있었습니다."라고 말했습니다. 회의에서 다른 사람이 저에게 전화를 걸었습니다. 물론 Restlet을 사용하여 회의에서 얻을 수있는 (매우 간단한) 기능으로 작동하는 REST 서버를 실행할 수있었습니다. 그것은 꽤 매끄러웠다.

다음은 현재 시간을 반환하는 하나의 방법이있는 베어 본 서버입니다. 서버를 실행하고 127.0.0.1:12345/sample/time을 누르면 현재 시간이 반환됩니다. 여기

import org.restlet.Application; 
import org.restlet.Component; 
import org.restlet.Context; 
import org.restlet.Restlet; 
import org.restlet.data.Protocol; 
import org.restlet.routing.Router; 

/** 
* This Application creates an HTTP server with a singple service 
* that tells you the current time. 
* @author corsiKa 
*/ 
public class ServerMain extends Application { 

    /** 
    * The main method. If you don't know what a main method does, you 
    * probably are not advanced enough for the rest of this tutorial. 
    * @param args Command line args, completely ignored. 
    * @throws Exception when something goes wrong. Yes I'm being lazy here. 
    */ 
    public static void main(String...args) throws Exception { 
     // create the interface to the outside world 
     final Component component = new Component(); 
     // tell the interface to listen to http:12345 
     component.getServers().add(Protocol.HTTP, 12345); 
     // create the application, giving it the component's context 
     // technically, its child context, which is a protected version of its context 
     ServerMain server = new ServerMain(component.getContext().createChildContext()); 
     // attach the application to the interface 
     component.getDefaultHost().attach(server); 
     // go to town 
     component.start(); 

    } 

    // just your everyday chaining constructor 
    public ServerMain(Context context) { 
     super(context); 
    } 

    /** add hooks to your services - this will get called by the component when 
    * it attaches the application to the component (I think... or somewhere in there 
    * it magically gets called... or something...) 
    */ 
    public Restlet createRoot() { 
     // create a router to route the incoming queries 
     Router router = new Router(getContext().createChildContext()); 
     // attach your resource here 
     router.attach("/sample/time", CurrentTimeResource.class); 
     // return the router. 
     return router; 
    } 

} 

그리고

는 사용하는 '현재 시간 자원'입니다 :

import org.restlet.representation.Representation; 
import org.restlet.representation.StringRepresentation; 
import org.restlet.resource.Get; 
import org.restlet.resource.ServerResource; 

/** 
* A resource that responds to a get request and returns a StringRepresentaiton 
* of the current time in milliseconds from Epoch 
* @author corsiKa 
*/ 
public class CurrentTimeResource extends ServerResource { 

    @Get // add the get annotation so it knows this is for gets 
    // method is pretty self explanatory 
    public Representation getTime() { 
     long now = System.currentTimeMillis(); 
     String nowstr = String.valueOf(now); 
     Representation result = new StringRepresentation(nowstr); 
     return result; 
    } 
} 
+0

당신은 뭔가 이해해야, 나는 REST 호출을 통해 들어오는 연결을 수신 대기 자바 사용자 정의, HTTP 서버와 마찬가지로, 서버를 만드는 데 관심이 있어요. 내가 Restlet을 사용할 수 있습니까? – DarthVader

+1

예, Restlet을 사용하여이를 수행 할 수 있습니다. – corsiKa

+0

나는 그것을 시도 할 것이다. 감사. – DarthVader

2

JAX-RS 자바로 REST를위한 API이다. 많은 구현이 있지만 주요한 것들은 Jersey (참조 구현), Apache의 CXF 및 Restlet입니다.

0

나는 HTTP 기반의 RESTful 서비스와 관련 있다고 말할 것이다. 급속하게 defacto 표준이되고 있습니다. 장단점을 확인하려면 similar question에 대한 내 대답을 확인하십시오.

1

다운로드 JBoss 7. 문제가 해결되었습니다.

Heres는 편안한 서비스 :

@Path("/myservice") 
public class MyService { 

    @GET 
    @Produces(MediaTypes.TEXT_PLAIN) 
    public String echoMessage(@QueryParam("msg") String msg) { 
     return "Hello " + msg; 
    } 
} 

가 WAR을 만듭니다. 배포. 브라우저를 열고 http://myserver/myapp/myservice?msg=World으로 가십시오. 끝난!

+0

권. 나는 jboss가 빤다는 것을 들었다. – DarthVader

+0

누가 그렇게 말했습니까? JBoss 6는 심각한 성능 문제를 가지고 있었지만 그 시리즈는 항상 견고했습니다. JBoss 7은 살인자입니다. – Perception

+0

내가 그 병을 필요합니까? 어떤 API를 사용합니까? – DarthVader

0

이것은 가장 좋은 방법입니다. 스프링 MVC는 많은 REST 기능을 가지고 있습니다. 이것은 단지 하나의 jar 파일을 포함합니다. 그리고 당신은 모든 기능을 모두 사용하도록되어 있습니다. 아래의 녀석이 JBOSS에서 설명하는 것처럼 간단하고 훨씬 더 유연합니다.

http://java.dzone.com/articles/spring-30-rest-example

2

일반적으로, 당신은 서버를 생성하지 않습니다. 웹 응용 프로그램을 만들어 서버 또는 서블릿 컨테이너에 배포합니다. 일부 서블릿 컨테이너는 웹 애플리케이션에 내장 가능합니다. 둑. Poppular free 서블릿 컨테이너는 Tomcat, Glassfish, Jetty 등입니다.

Restlet의 경우 서블릿 컨테이너가 아닙니다. RESTful 스타일로 wep 애플리케이션을 만들 수있는 프레임 워크이다. 그래서 이것은 혼동되어서는 안됩니다.

서블릿 컨테이너를 사용하기로 결정했다면 문제는 RESTful 스타일로 웹 애플리케이션을 만드는 방법이다. REST는 기술이 아닙니다. 설계 원칙입니다. 그것은 당신이 인터페이스를 어떻게 만들어야하는지에 대한 개념이다.

REST의 디자인은 상태 비 저장이므로 트랜잭션 상태를 저장할 필요가 없습니다. 요청에 대한 모든 정보는 클라이언트에게 응답을 생성하기에 충분해야합니다.

REST 스타일을 쉽게 구현할 수있는 서블릿 프레임 워크가 여러 개 있습니다. 일부는 매우 정교합니다. 스프링 프레임 워크.

0

저는 JBoss 6를 RestEasy과 함께 사용합니다. 나는 here에있는 자습서를 만들었습니다. 나는 이것이 당신을 돕기를 바랍니다.

0

또한 REST 서버 구현 here에 대한 간단한 예제를 볼 수 있습니다.