2011-07-28 162 views
0

我在C#中編寫用於套接字通信的小程序。我這裏還有我的代碼: 客戶端(數據發送方):套接字通信錯誤

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 
using System.Net.Sockets; 

namespace Client 
{ 
class Program 
{ 
    static Socket sck; //vytvor socket 
    static void Main(string[] args) 
    { 
     sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234); //nastav premennú loacalEndPoint na lokálnu ip a port 1234 
     try //Skús sa 
     { 
      sck.Connect(localEndPoint); // pripojiť 

     } 
     catch { //ak sa to nepodarí 
      Console.Write("Unable to connect to remote ip end point \r\n"); //vypíš chybovú hlášku 
      Main(args); 
     } 

     Console.Write("Enter text: "); 
     string text = Console.ReadLine(); 
     byte[] data = Encoding.ASCII.GetBytes(text); 
     sck.Send(data); 
     Console.Write("Data sent!\r\n"); 
     Console.Write("Press any key to continue..."); 
     Console.Read(); 
     sck.Close(); 
    } 
} 
} 

服務器(數據reciver):

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 
using System.Net.Sockets; 


namespace Server 
{ 
class Program 
{ 
    static byte[] Buffer { get; set; } //vytvor Buffer 
    static Socket sck; 

    static void Main(string[] args) 
    { 
     sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //vytvor Socket 
     sck.Bind(new IPEndPoint(0, 1234)); 
     sck.Listen(80); 
     Socket accepted = sck.Accept(); 
     Buffer = new byte[accepted.SendBufferSize]; 
     int bytesRead = accepted.Receive(Buffer); 
     byte[] formatted = new byte[bytesRead]; //vytvor novú Array a jej dĺžka bude dĺžka priatých infomácii 
     for(int i=0; i<bytesRead;i++){ 
      formatted[i] = Buffer[i]; //načítaj z Buffer do formatted všetky priate Bajty 

     } 
     string strData = Encoding.ASCII.GetString(formatted); //z ASCII hodnôt urob reťazec 
     Console.Write(strData + "\r\n"); //vypíš data 
     sck.Close(); //ukonči spojenie 


    } 
} 

} 我的問題是:在客戶端程序,我在1234端口上發送數據到本地ip。但我無法連接。我試過端口80,它已連接。所以,請問我的問題在哪裏?我怎樣才能連接到每個人的端口?請忽略代碼中的評論,並請幫助我。

+0

檢查你的防火牆。 – Odys

+0

這些程序寄存器(解鎖)端口,當你安裝它們。 – Odys

+0

我現在不工作,我有一些代碼,並且我擁有所有防火牆關閉。哪裏可以成爲問題? – FrewCen

回答

1

您正在監聽端口80,即您的客戶端程序應連接的端口。 「1234」是服務器綁定的LOCAL端口。沒有什麼是在該端口上收聽。

1

服務器在哪個ip上監聽?你用netstat -an |檢查了嗎?找到「聽」|找到「1234」? (注意:替換聽你的語言表達...)。

0可能不是127.0.0.1,但第一個NIC的第一個分配的IP地址......(雖然0應該聽取所有接口...但是,唉......

我會一直使用IP-不會忽略在這兩個,在客戶端和服務器

心連心

馬里奧