2010-12-14 96 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); 
    }