2010-07-15 31 views
3

我正在使用ActionScript連接到C#套接字服務器。 在客戶端(動作腳本),我使用以下方法來發送數據:關於使用.Net的ActionScript套接字通信的幫助

var socket:Socket = new Socket("localhost", 8080); 
socket.writeUTF("hello"); 
socket.flush(); 

在服務器(C#4.0),我用這個:

server = new TcpListener(IPAddress.Any, 8080); 
server.Start(); 
TcpClient client = server.AcceptTcpClient(); 
BinaryReader reader = new BinaryReader(client.GetStream(), Encoding.UTF8); 
Console.WriteLine(reader.ReadString()); 

我能夠連接槽閃光到服務器。但服務器沒有收到來自客戶端的消息(「hello」)。服務器只是忽略它沒有發送的消息。但是當我再次執行reader.ReadString()時,我收到消息(所以我必須讀兩次才能獲得每個輸入)。

我想我知道這個問題 - 這是Flash如何寫入字符串: http://livedocs.adobe.com/flex/3/langref/flash/net/Socket.html#writeUTF()

這是C#如何讀取它: http://msdn.microsoft.com/en-us/library/system.io.binaryreader.read7bitencodedint.aspx

關於C#如何讀取它aditional的信息(看在備註):http://msdn.microsoft.com/en-us/library/system.io.binarywriter.write7bitencodedint.aspx

有誰可以告訴我如何使客戶端和服務器使用二進制數據進行通信?
謝謝,Moshe。

+0

您是否在'writeUTF()'description:'中錯過了以下內容:「注意:由此方法編寫的數據不會立即傳輸;它將被排隊直到flush()方法被調用。 ? – 2010-07-15 19:05:55

+0

哦,在我的完整代碼中,我使用'socket.flush()',但我忘記寫在這裏。所以它甚至在沖水時也不起作用。 – 2010-07-15 19:29:37

回答

0

嘿的Zippo寫從閃存一個字節是:

socket.writeByte(byte) 

而且這裏是服務器的代碼段,我寫來處理讀取客戶端的數據。

 NetworkStream clientStream = tcpListener.AcceptTcpClient().GetStream(); 

     byte[] message = new byte[4096]; 
     int bytesRead; 

     while (true) 
     { 
      bytesRead = 0; 

      try 
      { 
       //blocks until a client sends a message 
       bytesRead = clientStream.Read(message, 0, 4096); 
      } 
      catch 
      { 
       //a socket error has occured 
       break; 
      } 

      if (bytesRead == 0) 
      { 
       //the client has disconnected from the server 
       break; 
      } 

      //message has successfully been received 
      ASCIIEncoding encoder = new ASCIIEncoding(); 
      String received = encoder.GetString(message, 0, bytesRead); 

      for (int i = 0; i < bytesRead; i++) 
      { 
       if (message[i] == MESSAGE_BEGIN) 
       { 
       player.currentMessage = new Message(); 
       } 
       else if (message[i] == MESSAGE_END) 
       { 
       _GotMessage(player, player.currentMessage); 
       } 
       else if (message[i] == TYPE_BEGIN) 
       { 
       player.currentString = ""; 
       } 
       else if (message[i] == TYPE_END) 
       { 
       player.currentMessage.Type = player.currentString; 
       } 
       else if (message[i] == STRING_PARAM_BEGIN) 
       { 
       player.currentString = ""; 
       } 
       else if (message[i] == STRING_PARAM_END) 
       { 
       int val; 
       bool isInt = Int32.TryParse(player.currentString, out val); 
       if (isInt) 
       { 
        player.currentMessage.content.Add(val); 
       } 
       else 
       { 
        player.currentMessage.content.Add(player.currentString); 
       } 
       } 
       else 
       { 
       player.currentString += System.Convert.ToChar(message[i]); 
       } 
      } 
     } 

我包括了所有我的代碼,只是要完成,但如果您有任何問題,請不要猶豫,問。服務器位於C#