2015-12-19 97 views
0

我創建一個小的聊天(1-1)申請學習網絡編程和創建套接字時使用TCP協議拒絕後,Socket.Connect()總是返回錯誤10061 然而,如果我使套接字UDP,我沒有看到問題。連接通過TCP套接字錯誤#10061

這裏是我的代碼:

myEndPoint = new IPEndPoint(IPAddress.Parse(_txtMyIPAdress.Text), int.Parse(_txtMyPort.Text)); 
TargetSideEndPoint = new IPEndPoint(IPAddress.Parse(_txtTargetIPAddress.Text), int.Parse(_txtTargetPort.Text)); 
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
mySocket.Bind(myEndPoint); 
mySocket.Connect(TargetSideEndPoint); 
byte[] receivedBuffer = new byte[MAX_BUFFER_SIZE = 1024]; 
ReceivePackets(mySocket, receivedBuffer);//My function 

任何一個能幫助我嗎? 更新: 我不使用聽()的問題是,當我調用Connect() 我已經嘗試過多個端口使用相同的問題,我目前從我的應用程序中打開兩個實例,並使用2 1臺測試PC上防火牆關閉時不同的端口。

感謝,

+0

可能重複的[TCP套接字錯誤10061](http://stackoverflow.com/questions/9077606/tcp-socket-error-10061) –

+0

另請檢查[此問題](http://stackoverflow.com/questions/9695224 /無連接可待定製的,因爲最target機器積極-拒絕-IT-127-0) –

+0

還發布了聽衆的代碼。 –

回答

0

對於TCP,這是一個面向連接的協議,你需要一臺服務器和客戶端。

服務器必須監聽傳入連接和客戶端應該發起連接。然後,客戶端將能夠與服務器進行通信並交換數據。

下面是一個簡單的工作示例:

void Main() 
{ 
    Console.WriteLine("Starting listener thread"); 
    Thread serverThread = new Thread(ListenerThreadProc); 
    serverThread.Start(); 

    Console.WriteLine("Waiting 500 milliseconds to allow listener to start"); 
    Thread.Sleep(500); 

    Console.WriteLine("Client: Connecting to server"); 
    TcpClient client = new TcpClient(); 
    client.Connect(IPAddress.Loopback, 12345); 
    Console.WriteLine("Client: Connected to server"); 

    byte[] buffer = new byte[5]; 
    Console.WriteLine("Client: Receiving data"); 
    using (NetworkStream clientStream = client.GetStream()) 
     clientStream.Read(buffer, 0, buffer.Length); 

    Console.WriteLine("Client: Received data: " + buffer.Aggregate("", (s, b) => s += " " + b.ToString()));  
} 

void ListenerThreadProc() 
{ 
    TcpListener listener = new TcpListener(IPAddress.Any, 12345); 
    listener.Start(); 
    Console.WriteLine("Server: Listener started"); 

    Console.WriteLine("Server: Waiting for client to connect"); 
    TcpClient client = listener.AcceptTcpClient(); 
    Console.WriteLine("Server: Client connected"); 

    listener.Stop();  
    Console.WriteLine("Server: Listener stopped"); 

    Console.WriteLine("Server: Sending data"); 
    byte[] buffer = new byte[] { 1, 2, 3, 4, 5 }; 
    using (NetworkStream clientStream = client.GetStream()) 
     clientStream.Write(buffer, 0, buffer.Length); 
    Console.WriteLine("Server: Sent data"); 
} 

在這個例子中,做出,因爲它得到簡單,你有一臺服務器接受單個客戶端,以它發送一些數據。客戶端連接,讀取數據,然後顯示它。

一個真實的服務器將拆分新的線程(或任務,異步模式),以儘快滿足客戶的要求爲客戶端將連接並進行監聽新的連接。