0
我是新來的java套接字,我想創建一個簡單的UDP傳輸使用客戶端服務器。我現在的問題是服務器正在運行無限循環,而不是將消息發送到客戶端。很抱歉,如果我做了一些愚蠢的錯誤,感謝java套接字UDP雙向使用數據報
服務器:
import java.net.*;
import java.util.*;
class EchoServer {
public static void main(String args[]) throws Exception {
DatagramSocket socket = new DatagramSocket(54373);
DatagramPacket packet = new DatagramPacket(new byte[512],512);
String temp = "Hello client";
byte[] buffer = temp.getBytes();
while (true) {
socket.receive(packet);
System.out.println("Received from client");
DatagramPacket packet2 = new DatagramPacket(buffer,buffer.length,InetAddress.getByName("127.0.0.1"),54373);
socket.send(packet2);
}
}
}
客戶:
import java.net.*;
import java.util.*;
class EchoClient {
public static void main(String args[]) throws Exception {
DatagramSocket socket = new DatagramSocket();
socket.setSoTimeout(5000);
byte[] buffer = "Hello Server".getBytes();
DatagramPacket packet = new DatagramPacket(buffer,buffer.length,InetAddress.getByName("127.0.0.1"),54373);
socket.send(packet);
DatagramPacket packet2 = new DatagramPacket(new byte[512],512);
socket.receive(packet2);
System.out.println("Received from server");
}
}
然而,我的服務器是能夠發送原來的 「包」,而不是packet2