2010-12-16 80 views
0

我怎样才能做一个程序,可以做消息.....如果我发送消息,它是由用户和用户回复达到我..套接字编程。 c#.net

+1

现在这个问题是*非常*一般。更具体的东西将允许更具体的答案。 – Richard 2010-12-16 09:22:15

回答

0

检查此代码,它是从应用程序与java编码的第二个通信:

using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Net; 
    using System.Net.Sockets; 
    using System.IO; 
    public class TcpCommunication 
     { 
      private TcpListener commListener; 
      private TcpClient client; 
      private StreamReader reader; 

      public TcpCommunication(int port) 
      { 
       this.commListener = new TcpListener(new IPAddress(new byte[]{127,0,0,1}),port); 
      } 

      public bool isAlive() 
      { 
       return client != null && this.client.Connected; 
      } 

      public void waitForClient() 
      { 
       this.commListener.Start(); 
       this.client = commListener.AcceptTcpClient(); 
       this.reader = new StreamReader(client.GetStream()); 
       this.commListener.Stop(); 
      } 

      public String getStringLine() 
      { 
       return reader.ReadLine(); 
      } 

      public void writeStringLine(String commString) 
      { 
       commString = commString.Replace('\n','\t'); 

       NetworkStream networkStream = client.GetStream(); 
       System.Text.UTF8Encoding encoding = new UTF8Encoding(); 
       Byte[] stringInByteFormat = encoding.GetBytes(commString + "\n");     networkStream.Write(stringInByteFormat,0,stringInByteFormat.Length); 
        } 
0

有很多方法可以这样做。

  • 您可以使用套接字(System.Net.Sockets命名空间,开始关注类TcpClientTcpListener)。这是一个非常低层次的方法,你必须自己做所有事情。
  • 您可以使用Web服务或WCF等通信编程现有的抽象层之一,我会推荐它。请参阅this question and answers开始阅读的地方。
0

做到这一点,最好的方法是使用WCF(Windows通信基础),只是使用net.tcp绑定。

http://msdn.microsoft.com/library/dd943056.aspx

基本上,而不必创建和整个插座元帅的消息,你告诉在配置文件中创建一个WCF服务(在代码仅仅是接口和它的实现有几个属性),然后它监听一个tcp套接字而不是http。

您还可以将其配置为双工模式 - 这是双向模式。