2010-12-14 93 views
1

我正在製作一個c#messenger應用程序,只是爲了好玩,但我想做的很好。 我想要發送聊天消息,踢球命令等命令的可能性,但我不知道控制它的好方法。我可以通過網絡流發送一個對象,或者我可以發送一個字符串,如:stream.write(「command ##」);c#messenger,通過網絡發送命令,協議?

也許你知道另一種方法來解決這個問題,但我在stackoverflow atm。 謝謝。

+4

我會使用WCF,讓微軟完成所有的硬聯網工作給你。 – 2010-12-14 21:07:06

+1

解釋舊的引用:「有些人在遇到問題時說:'我知道,我會使用WCF。'現在他們有兩個問題。「我同意,WCF和Net.TCP之類的雙工綁定之一可能是解決這個問題的最佳方法:我的觀點是,即使使用WCF,MS仍然需要大量的努力。 – 2010-12-14 21:21:05

回答

0

只是有一些控制字符(如)...當服務器看到該字符時,它開始記錄,直到它收到一個空格字符。一旦它遇到空間,它會查看字符串並將其與可用命令列表(\ kick等)進行比較。

這只是解決這個問題的一種技術。老實說,如果你是爲了娛樂而做的,那就實現它吧:-)

0

如果你想把你的「樂趣」項目變成一個「專業發展」項目(如在,發展你的技能,而不是專業品質)嘗試WCF。它將爲您處理整個消息架構,並讓您專注於您的功能。另外,WCF在簡歷上看起來不錯。

1

看起來你似乎已經在你的問題中使用Stream.Write()來建立你的套接字了。

您可能想嘗試一些構建帶有消息類型和某種校驗和的字節數組。例如:

 string message = "this is your message"; 
     byte packetType = 1; 
     byte checksum = 0; 

     // calculate a simple checksum 
     foreach (char c in message) 
     { 
      checksum ^= (byte)c; 
     } 


     // type, message, checksum into buffer 
     // (uses list instead of playing with arrays for expeditious example code) 
     List<byte> buffer = new List<byte>(); 
     buffer.Add(packetType); 
     buffer.AddRange(ASCIIEncoding.UTF8.GetBytes(message)); 
     buffer.Add(checksum); 

     // write out to the socket 
     CommStream.Write(buffer.ToArray(), 0, buffer.Count); 

,一旦你覺得adventerous超越發送簡單的字符串,你可以嘗試使用運行時命名空間序列化對象的字節數組:

using System.IO; 
    using System.Runtime.Serialization.Formatters.Binary; 

    public class Message : ISerializable 
    { 
     DateTime timestamp; 
     byte type; 
     string message; 
    } 

    public byte[] BuildBuffer(Message input) 
    { 
     // Serialize the message 
     Stream s = new MemoryStream(); 
     BinaryFormatter binaryFormatter = new BinaryFormatter(); 
     binaryFormatter.Serialize(s, input); 
     buffer = s.ToArray(); 

     return buffer; 
    } 

    public Message BuildMessage(byte[] input) 
    { 
     Stream s = new MemoryStream(input); 
     s.Position = 0; 

     BinaryFormatter binaryFormatter = new BinaryFormatter(); 
     return (Message)binaryFormatter.Deserialize(s); 
    }