2012-10-09 22 views
-2

我想製作一個程序,它像一個即時通訊工具,我已經完成,但我不知道如何發送/接收字符串到特定的IP地址。C#:如何發送/接收字符串到本地網絡中的特定IP地址

我包括我自己在那裏這東西屬於一種方法:

//is called every second and when you commit a message 
public void Update(ref eStatus prgmStatus, ref eProfile userProfile) 
{ 
    UpdateUI(ref prgmStatus); 
    [ Some other Update Methods ] 
    [ Catch the string and add it to userProfile.CurrentChatHistory] 
} 

public void EnterText(object sender, EventArgs e) 
{ 
    _usrProfile.CurrentChatHistory.Add(chatBox.Text); 
    [ send chatBox.Text to IP 192.168.0.10 (e.g.) ] 
} 

我想用一個客戶端到客戶端系統無需任何額外的服務器軟件運行。

我可以使用哪些系統命名空間和方法來實現此目的?

+1

Google上的第一個結果:http://www.codeproject.com/Articles/12893/TCP-IP-Chat-Application-Using-C – Nasreddine

+1

Internet上有很多關於C#的網絡教程。 –

+0

這沒什麼用,因爲我的程序是客戶端客戶端的客戶端,沒有任何服務器 – Paedow

回答

2

System.Net命名空間是您需要查看的位置。

如果您正在進行點對點聊天,您可能需要將消息發送到多個IP地址,而沒有中央服務器,則最好使用UDP。

從你的評論中可以看出你沒有中央服務器,我建議你至少在開始時使用UDP來快速啓動。 UdpClient class是你的朋友,允許你發送數據包到任何指定的網絡地址。

你基本上可以創建一個新的UdpClient實例,將一個已知的端口號傳遞給綁定到構造函數中。

然後,使用Receive方法讀取該端口上的數據包。

然後,您也可以使用同一實例上的發送方法將數據包發送到網絡地址。

0

我在之前發佈了另一個問題。如果你想使用異步/等待.Net4.5的特點,這裏有一個簡單的EchoServer應該讓你開始:

void Main() 
{ 
    CancellationTokenSource cts = new CancellationTokenSource(); 
    TcpListener listener = new TcpListener(IPAddress.Any,6666); 
    try 
    { 
     listener.Start(); 
     AcceptClientsAsync(listener, cts.Token); 
     Thread.Sleep(60000); //block here to hold open the server 
    } 
    finally 
    { 
     cts.Cancel(); 
     listener.Stop(); 
    } 

    cts.Cancel(); 
} 

async Task AcceptClientsAsync(TcpListener listener, CancellationToken ct) 
{ 
    while(!ct.IsCancellationRequested) 
    { 
     TcpClient client = await listener.AcceptTcpClientAsync(); 
     EchoAsync(client, ct); 
    } 

} 
async Task EchoAsync(TcpClient client, CancellationToken ct) 
{ 
    var buf = new byte[4096]; 
    var stream = client.GetStream(); 
    while(!ct.IsCancellationRequested) 
    { 
     var amountRead = await stream.ReadAsync(buf, 0, buf.Length, ct); 
     if(amountRead == 0) break; //end of stream. 
     await stream.WriteAsync(buf, 0, amountRead, ct); 
    } 
} 
+0

似乎真的很複雜......我不明白這個片段-.- – Paedow

+0

這就是爲什麼我問,我的應用程序是完整的,除了網絡部分,因爲我沒有得到它oo – Paedow

+0

好的,但你*真的*不明白。因此,您的問題確實屬於「過於寬泛」,應該關閉。 – spender

0

必須使用System.Net.Socket類創建一個客戶機/服務器體系結構。

該服務器可以是第三臺計算機或其中一個喋喋不休。如果選擇第二個選項,第一個開始聊天的人必須在特定端口上運行偵聽套接字,第二個人必須使用IP地址和端口連接到它。

相關問題