2012-07-08 217 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

相关问题