2013-06-04 221 views
0

我有问题。为什么我的客户端无法从服务器接收数据?服务器从客户端接收数据没有问题。是否因为我的客户端没有连接到我的服务器客户端上。有人有任何想法?对于我的英语感到抱歉,我来自捷克共和国。 :)UDP服务器和UDP客户端

这是我的UDP客户端:

UdpClient client; 
    public IPAddress serverIP = IPAddress.Parse("127.0.0.1"); 
    public Form1() 
    { 
     InitializeComponent(); 
     client = new UdpClient(); 
    } 

    public void SendData() 
    { 
     client.Connect(serverIP, 3000); 
     byte[] data = Encoding.ASCII.GetBytes("Hi, I'm new client."); 
     client.Send(data, data.Length); 
     DoListening(); 
    } 
    public void DoListening() 
    { 
     IPEndPoint adress = new IPEndPoint(serverIP, 3000); 
     byte[] receivedbytes = client.Receive(ref adress); 
     string recieved = Encoding.ASCII.GetString(receivedbytes); 

     MessageBox.Show("Recieved: " + recieved); 
    } 
    private void button1_Click(object sender, EventArgs e) 
    { 
     SendData(); 
    } 

这是我的UDP服务器:

public Form1() 
    { 
     InitializeComponent(); 
     Thread listening = new Thread(new ThreadStart(DoListening)); 
     listening.Start(); 
    } 
    public void ClientThread(Object adress) 
    { 
     IPEndPoint ip = adress as IPEndPoint; 
     UdpClient client = new UdpClient(); 
     client.Connect(ip); 
     byte[] data = Encoding.ASCII.GetBytes("No nazdar"); 
     client.Send(data, data.Length); 
     MessageBox.Show("Sending data.."); 
    } 
    public void DoListening() 
    { 
     while (true) 
     { 
      UdpClient client = null; 
      client = new UdpClient(3000); 
      IPEndPoint host = new IPEndPoint(IPAddress.Any, 0); 
      MessageBox.Show("Listening"); 
      byte[] receivedbytes = client.Receive(ref host); 
      string recieved = Encoding.ASCII.GetString(receivedbytes); 
      MessageBox.Show("Client " + host.Address.ToString() + " conected. Message: " + recieved); 
      new Thread(new ParameterizedThreadStart(ClientThread)).Start(host); 
      Console.WriteLine("Doslo k vyjimce z duvodu : {0}", ex.SocketErrorCode); 
     } 
    } 
+0

可能的重复:http://stackoverflow.com/questions/16919469/c-sharp-application-simply-not-receiving-udp-data#comment24423243_16919469 – C4stor

+0

不,我正在看这个线程,它不是同一个问题。请不要告诉我什么是可能的重复,只是回答我的线索请求.. – Naxmars

+0

所以没有人知道? – Naxmars

回答

0

不知道,但我认为你试图连接到本地主机

UdpClient client; 
public IPAddress serverIP = IPAddress.Parse("127.0.0.1"); 
public Form1() 
{ 
    InitializeComponent(); 
    client = new UdpClient(); 
} 

public void SendData() 
{ 
    client.Connect(serverIP, 3000); 

你正在连接到你自己。您需要更改实际的服务器IP地址127.0.0.1 ...

////我假设客户端和服务器不在同一台设备上。

+0

他们是:-((很老的话题) – Naxmars