2011-04-11 4 views
1

내 wcf 응용 프로그램의 서버 부분과 여전히 고생하고 있습니다.WCF 개체에서 "System.NullReferenceException 처리되지 않았습니다"

문제는 서버 클래스 내에서 "콜백"개체를 만드는 경우 "System.NullReferenceException was unhandled"오류가 발생한다는 것입니다.

제대로 이해하면이 서버 개체를 만들 때 발생합니다. ServerClass myServer = new ServerClass();

그래서 나는 어떻게 든 서버 객체에 대한 목록을 만들고 클라이언트가 연결될 때마다이 객체를 자동으로 추가해야한다고 생각합니다 (&). 제발, 그 일을하는 가장 좋은 방법은 무엇입니까?

여기 내 코드는 지금까지의 :

namespace server2 
{ 
    public partial class Form2 : Form 
    { 
     public Form2() 
     { 
      InitializeComponent(); 
      myServer.eventHappened += new EventHandler(eventFunction); 
     } 

     ServerClass myServer = new ServerClass(); 
     // here I instance a new server object. 
     // yet I believe that I need to make a list, that would store this objects, so that multiple clients would be able to connect, 
     // and I would be able to pick, to whom I want to send a callback. 

     void eventFunction(object sender, EventArgs e) 
     { 
      label1.Text = myServer.clientName; 
     } 

     private ServiceHost duplex; 

     private void Form2_Load(object sender, EventArgs e)  /// once the form loads, create and open a new ServiceEndpoint. 
     { 
      duplex = new ServiceHost(typeof(ServerClass)); 
      duplex.AddServiceEndpoint(typeof(IfaceClient2Server), new NetTcpBinding(), "net.tcp://localhost:9080/service"); 
      duplex.Open(); 
      this.Text = "SERVER *on-line*"; 
     } 

    } 




    class ServerClass : IfaceClient2Server 
    { 

     public event EventHandler eventHappened; 

     IfaceServer2Client callback = OperationContext.Current.GetCallbackChannel<IfaceServer2Client>(); 
     // ERROR: System.NullReferenceException was unhandled 

     public string clientName = "noname"; 

     public void StartConnection(string name) 
     { 
      clientName = name; 
      MessageBox.Show(clientName + " has connected!"); 

      eventHappened(this, new EventArgs()); 
      // ERROR: System.NullReferenceException was unhandled :(

      callback.Message_Server2Client("Welcome, " + clientName); 
     } 

     public void Message_Cleint2Server(string msg) 
     { 
     } 

     public void Message2Client(string msg) 
     { 
     } 

    } 




    [ServiceContract(Namespace = "server", CallbackContract = typeof(IfaceServer2Client), SessionMode = SessionMode.Required)] 


    public interface IfaceClient2Server   ///// what comes from the client to the server. 
    { 
     [OperationContract(IsOneWay = true)] 
     void StartConnection(string clientName); 

     [OperationContract(IsOneWay = true)] 
     void Message_Cleint2Server(string msg); 
    } 


    public interface IfaceServer2Client   ///// what goes from the sertver, to the client. 
    { 
     [OperationContract(IsOneWay = true)] 
     void AcceptConnection(); 

     [OperationContract(IsOneWay = true)] 
     void RejectConnection(); 

     [OperationContract(IsOneWay = true)] 
     void Message_Server2Client(string msg); 
    } 

} 

감사합니다! 클래스 생성자에서 그 라인을 넣어

답변

2

이렇게하면 안됩니다. 우선 콜백 채널은 서비스 클래스 인스턴스가 생성 될 때가 아니라 작업 내에서만 사용할 수 있습니다.

두 번째로, ServerClass의 인스턴스는 WCF 구성에 따라 WCF 서비스 호스트에서 만들어집니다. 예를 들어, 호출 당 하나의 인스턴스 (!)가있을 수 있습니다. 따라서 인스턴스를 직접 만들고 이벤트 핸들러를 첨부해도 자동으로 생성 된 인스턴스에는 영향을주지 않습니다. 그렇기 때문에 StartConnection에서 예외가 발생합니다. 내가 그 경우에 할 거라고 무엇

은 다음과 같습니다

  1. 가 원하는 이벤트
  2. 기본 코드 내에서 이벤트에 핸들러를 연결 게시 싱글 톤 클래스를 만듭니다. 이
  3. 공개 방법을 만들기 이벤트를 수신하는 코드가 될 것이다 (ConnectionStarted을 같은) 당신이 이벤트를 기다릴 필요가 없습니다 경우 ServerClass

에서 이벤트를

  • 콜이 방법을 제기하는 처리기를 종료하면 별도의 스레드에서 비동기 적으로 이벤트를 발생시킬 수도 있습니다. 그런 다음 2 단계에서 연결된 이벤트 처리기가 this.Invoke (Forms) 또는 this.Dispatcher.BeginInvoke (WPF)과 같이 스레드 컨텍스트를 제대로 처리하는지 확인해야합니다.

  • 0

    시도 :

    class ServerClass : IfaceClient2Server 
    { 
        public event EventHandler eventHappened; 
        IfaceServer2Client callback; 
    
        public ServerClass() 
        { 
         callback = OperationContext.Current.GetCallbackChannel<IfaceServer2Client>(); 
        } 
    
        ... 
    } 
    

    여전히 아마 의미 운은 당신이 일부 작동 내부 OperationContext.Current을 사용하지 할 수 있습니다.

    +0

    아니요, 동일한 "System.NullReferenceException 처리되지 않은"두 callback = OperationContext.Current.GetCallbackChannel (); 및 eventHappened (this, new EventArgs()); – Roger

    +0

    내가 말했듯이, 당신의 논리는 'OperationContext.Current' 자체가'null'이므로 다시 생각할 필요가 있습니다 - Thorsten 대답을보십시오. :) –

    관련 문제