2010-12-16 82 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。

您還可以將其配置爲雙工模式 - 這是雙向模式。