2014-10-30 181 views
1

我正在寫一個websockets-client。我有兩個問題:服務器沒有收到消息

  1. 當我關閉應用程序的窗口一臺服務器出現故障

  2. 服務器沒有收到消息,但客戶端總是從服務器接收到的問候信息。

System.Exception的:你必須通過的WebSocket後的WebSocket是 打開

客戶在C#(Websocket4Net LIB)

private static void _clientSocket_Closed(object sender, EventArgs e) 
{ 
    if (_clientSocket.State == WebSocket4Net.WebSocketState.Open) 
    { 
     _clientSocket.Close("Closed by user"); 
    } 
} 

public static void WebRequest(string url, dutyObject objToSend) 
{ 
    _clientSocket = new WebSocket(url); 

    _clientSocket.MessageReceived += _clientSocket_MessageReceived; 
    _clientSocket.DataReceived += _clientSocket_DataReceived; 
    _clientSocket.Closed += _clientSocket_Closed; 
    _clientSocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(_clientSocket_Error); 

    _clientSocket.Open(); 

    var jsonMessage = JsonSerializeHelper.Serialize(objToSend); 
    _clientSocket.Send(jsonMessage); 
} 

服務器上的PHP發送數據

class Server extends WebSocketServer 
{ 
    protected function serverCreated() 
    { 
    } 

    /** 
    * This is run when server is receiving data. 
    */ 
    protected function process($connected_user, $message) 
    { 
     $this->send($connected_user,"[+]".$message); //just echo reply 
    } 

    /** 
    * This is run when socket connection is established. Send a greeting message 
    */ 
    protected function connected($connected_user) 
    { 
     $welcome_message = 'Welcome to Service. Service works with JSON. Be careful!'; 
     $this->send($connected_user, $welcome_message); 
    } 


    protected function closed($connected_user) 
    { 
     $this->stdout("User closed connection \n"); 
    } 
} 

客戶端更新。

while (_clientSocket.State != WebSocketState.Open) 
      { 
       if (_clientSocket.State == WebSocket4Net.WebSocketState.Open) 
       { 
        Console.WriteLine(_clientSocket.State); 
        _clientSocket.Send(ecn.GetBytes(jsonMessage), 0, ecn.GetBytes(jsonMessage).Length); 
       } 
       else 
       { 
        Console.WriteLine("E: " + _clientSocket.State); 
        //_clientSocket.Close();  
       }  
      } 

它永久的說「連接」。

+0

請這個話題:( – Serg 2014-10-31 04:48:13

+0

在錯誤提示代碼時定時問題,你確定套接字在數據發送之前已經連接好了嗎?錯誤的做法是假定連接已經連接,在發送數據之前檢查狀態 – Wranorn 2014-10-31 05:37:13

+0

@Wranorn,查看更新後的代碼客戶端套接字凍結在「連接「狀態 – Serg 2014-10-31 06:34:19

回答

0

我懷疑這可能是與握手錯誤 - 看着我看到,如果沒有握手作出這個錯誤被拋出

private bool EnsureWebSocketOpen() 
     { 
      if (!Handshaked) 
      { 
       OnError(new Exception(m_NotOpenSendingMessage)); 
       return false; 
      } 

      return true; 
     } 
相關問題