2012-05-04 107 views
2

我的一個程序遇到了一些問題。 這裏是它如何工作:C#UDP套接字不聽取響應?

  1. C#的客戶端將數據發送到Java服務器
  2. Java服務器檢查數據
  3. Java服務器發回C#的客戶端命令
  4. C#客戶端接收數據,並使用戶登錄或註冊

我設法得到,直到第3步,但現在我卡住在步驟4

我在服務器和客戶端以及服務器上運行Wireshark。 所有軟件包都能正確進出。 服務器收到一個數據包並給出一個數據包。 客戶給出一個並接收一個。 但是,如果我在控制檯中檢查netstat,我看不到任何開放端口。 其實我根本沒有看到任何UDP套接字。 因此,數據包進來,但C#客戶端似乎不聽,爲什麼?

這是C#客戶端。

// Opening a socket with UDP as Protocol type 
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
// The address of the server 
IPAddress[] address = Dns.GetHostAddresses("192.168.0.87"); 
// The Endpoint with the port 
IPEndPoint endPoint = new IPEndPoint(address[0], 40001); 

// Defining the values I want 
string values = "Something I send here"; 
// Encoding to byte with UTF8 
byte[] data = Encoding.UTF8.GetBytes(values); 

// Sending the values to the server on port 40001 
socket.SendTo(data, endPoint); 

// Showing what we sent 
Console.WriteLine("Sent: " + values); 

// Timeout for later, for now I just let the program get stuck 
// socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000); 

// Allowing the response to come in from everywhere 
EndPoint response = new IPEndPoint(IPAddress.Any, 0); 
// Buffer for server response (currently bigger then actually necessary for debugging) 
byte[] responseData = new byte[1024]; 

//Receiving the data from the server 
socket.ReceiveFrom(responseData, ref response); 

// Outputing what we got, we don't even get here 
Console.WriteLine("You got: " + Encoding.UTF8.GetString(responseData)); 

// Closing the socket 
socket.Close(); 

對於調試,如果用戶驗證成功,我想發回字符串「測試」回來。

這裏是Java服務器

// Printing to the server that the user username logged in successfully 
System.out.println("User " + username + " logged in succesfully!"); 

// The byte buffer for the response, for now just Test 
byte[] responseData = "Test".getBytes("UTF-8"); 
// The Datagram Packet, getting IP from the received packet and port 40001 
DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length, receivePacket.getAddress(), 40001); 
// Sending the response, tried putting Thread.sleep here didn't help 
serverSocket.send(responsePacket); 

我希望我做了錯誤的C#客戶端在接收一部分,但不知道是什麼,任何意見或建議?

+0

通常情況下,您需要在發送任何要發送的郵件時關閉套接字。你有沒有試過關閉'serverSocket'? – npinti

+1

我想你錯過了在客戶端代碼中綁定的調用。 – wolfcastle

+0

@nptini我不能在它關閉後再訪問套接字,但我也嘗試過使用UdpClient和一個新的套接字,但仍然無法工作。 – user1137183

回答

1

我相信你錯過了在客戶端套接字綁定調用。

// Allowing the response to come in ON port 40001 
EndPoint response = new IPEndPoint(IPAddress.Any, 40001); 

socket.Bind(response); // bind to port 40001 on some local address 
+0

這樣做,謝謝。完全忘了那個... – user1137183

2

也許不是問題,但通常UDP響應被髮送回原始請求的源(源)端口。您正在將響應發送回固定端口。你可以嘗試更改Java位:

DatagramPacket responsePacket = new DatagramPacket(responseData, 
    responseData.length, receivePacket.getAddress(), receivePacket.getPort()); 
+0

謝謝你的迴應!錯誤是在C#部分,雖然添加socket.Bind()工作得很好,客戶端正在正確聽現在。 – user1137183