1
我已經編寫了UDP服務器客戶端程序。我面臨的問題是,當我運行服務器程序時,它不會等待客戶端連接。整個代碼在運行到結束之後執行。而當我在執行服務器端之間運行客戶端時,客戶端正在從其執行點接收數據。這裏是我的服務器代碼 -Udp服務器客戶端java
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(4321);
byte[] sendData;
String sentence = null;
FileInputStream file = new FileInputStream(new File("E:\\Deepak.txt"));
InetAddress IPAddress=InetAddress.getByName("localhost");
BufferedReader in = new BufferedReader(new InputStreamReader(file));
do{
while((sentence = in.readLine()) != null)
{
Thread.sleep(3000);
System.out.println(sentence);
sendData = sentence.getBytes();
DatagramPacket sendPacket =new DatagramPacket(sendData, sendData.length,IPAddress,9876);
serverSocket.send(sendPacket);
}
}while(true);
}
這裏是我的客戶端代碼 -
public static void main(String args[]) throws SocketException, UnknownHostException, IOException
{
DatagramSocket clientSocket = new DatagramSocket();
byte[] receiveData = new byte[1024];
String sentence ;
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
receivePacket.getLength();
System.out.println(receivePacket.getLength());
clientSocket.receive(receivePacket);
sentence = new String(receivePacket.getData());
}
}
可否請告訴我如何在UDP上實現自己的連接,如果我想要一個只在客戶端「連接」它時才發送數據的服務器。我是socket編程的新手。 –
難道不可以改變服務器來做'receive'嗎?這是最簡單的方法。 –
否。我的具體應用程序需要作爲發件人和客戶端作爲接收者實現。 –