2012-07-08 295 views
1

我正在處理C#(客戶端)和Python(服務器)之間的基本套接字通信,我不明白我從客戶端發生此錯誤的原因:C#客戶端Python服務器:連接被拒絕

[錯誤] FATAL UNHANDLED EXCEPTION:System.Net.Sockets.SocketException:連接被拒絕 at System.Net.Sockets.Socket.Connect(System.Net.EndPoint remoteEP)在/ private/tmp/monobuild/build中的[0x00159] /BUILD/mono-2.10.9/mcs/class/System/System.Net.Sockets/Socket_2_1.cs:1262 在System.Net.Sockets.TcpClient.Connect(System.Net.IPEndPoint remote_end_point)[0x00000]在/ private/tmp/monobuild/build/BUILD/mono-2.10.9/mcs/class/System/System.Net.Sockets/TcpClient.cs:284 at System.Net.Sockets.TcpCli ent.Connect(System.Net.IPAddress [] ipAddresses,Int32端口)/private/tmp/monobuild/build/BUILD/mono-2.10.9/mcs/class/System/System.Net.Sockets/TcpClient中的[0x000b3]的.cs:355個

我的計劃是真的很短,容易,所以我想這是一個noob問題,但我只是不明白這一點。我想要的只是一個客戶端向服務器發送一條消息,該消息將在控制檯上打印出來。

下面是C#客戶端(誤差來自:socket.Connect( 「本地主機」,9999);)

using System; 
using System.Net.Sockets; 

namespace MyClient 
{ 
class Client_Socket{ 
    public void Publish(){ 
TcpClient socket = new TcpClient(); 
socket.Connect("localhost",9999); 
NetworkStream network = socket.GetStream(); 
System.IO.StreamWriter streamWriter= new System.IO.StreamWriter(network); 
streamWriter.WriteLine("MESSAGER HARGONIEN"); 
streamWriter.Flush(); 
network.Close(); 
    } 

} 
} 

和Python的服務器:

from socket import * 

if __name__ == "__main__": 
    while(1): 
     PySocket = socket (AF_INET,SOCK_DGRAM) 
     PySocket.bind (('localhost',9999)) 
     Donnee, Client = PySocket.recvfrom (1024) 
     print(Donnee) 

THX您的幫助。

回答

4

你有兩個問題。首先是你對localhost有約束力。你可能想,如果你希望其他計算機能夠連接到綁定到0.0.0.0

PySocket.bind (('0.0.0.0',9999)) 

另一個問題是你與UDP服務,並試圖用TCP連接。如果你想使用UDP,你可以使用UdpClient而不是TcpClient。如果您想使用TCP,則必須使用SOCK_STREAM而不是SOCK_DGRAM,並使用listen,acceptrecv而不是recvfrom

+0

非常感謝,我會盡力。 – ssx 2012-07-08 21:29:23

相關問題