import java.io.*;
import java.net.*;
public class Server{
public static void main(String[] args) throws SocketException, IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int myPort= 2002;
String name;
String serverMsg;
String clientMsg;
byte[] dataReceive = new byte[65536];
byte[] sendData = new byte[65536];
DatagramPacket packetReceive = new DatagramPacket(dataReceive,dataReceive.length);
DatagramPacket sendPacket= new DatagramPacket(sendData,sendData.length);
DatagramSocket server= new DatagramSocket(myPort);
serverMsg="Pls enter your name:";
sendData=serverMsg.getBytes();
sendPacket.setData(sendData);
sendPacket.setAddress(packetReceive.getAddress());
sendPacket.setPort(packetReceive.getPort());
server.send(sendPacket);
server.receive(packetReceive);
clientMsg = new String(packetReceive.getData(),0,packetReceive.getLength());
serverMsg="yourname is "+clientMsg;
sendData=serverMsg.getBytes();
sendPacket.setData(sendData);
sendPacket.setAddress(packetReceive.getAddress());
sendPacket.setPort(packetReceive.getPort());
server.send(sendPacket);
server.close();
}
}
Exception in thread "main" java.lang.IllegalArgumentException: Port out of range:-1
at java.net.DatagramPacket.setPort(DatagramPacket.java:292)
at Server.main(Server.java:25)
sendPacket.setAddress(packetReceive.getAddress());
I'm not sure what you thought this line of code would do, but it doesn't make any sense. Despite its name, "packetReceive" does not (yet) hold a received packet. So "getAddress" cannot return the address it was sent from.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.