我是java网络的新手,我制作了一个客户端 - 服务器udp程序。服务器端工作正常但客户端没有从服务器接收任何内容。请更正错误。服务器端完全运行但客户端一直工作到最后。任何帮助都会很棒。
public class Client {
public static void main (String args[]) throws Exception {
DatagramSocket s = new DatagramSocket();
String msg = "Hello! ,from client. ";
byte[] b = msg.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(b, b.length, ia, 9999);
s.send(dp);
byte[] b2 = new byte[1024]; //byte array
DatagramPacket dip = new DatagramPacket(b2, b2.length);
s.receive(dip);
String str = new String(dip.getData());
System.out.println("From server" + str);
}
}
public class Server {
void run() throws Exception {
DatagramSocket ds = new DatagramSocket(9999);
byte [] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
String msg = new String(dp.getData());
System.out.println("Message from client:" + msg);
//giving back to client
String str = "HI!, from server.";
byte[] b2 = str.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dop = new DatagramPacket(b2, b2.length, ia, 9999);
ds.send(dop);
System.out.println("Message sent back");
ds.close();
}
public static void main(String args[]) throws Exception {
Server server = new Server();
server.run();
}
}
答案 0 :(得分:1)
您的服务器正在将所有响应发送到localhost,在端口9999.您需要更新服务器,以便它读取发件人的地址:
InetAddress ia = dp.getAddress();
int port = dp.getPort();
DatagramPacket dop = new DatagramPacket(b2, b2.length, ia, port);
答案 1 :(得分:0)
错误是您的服务器和客户端在同一主机上运行,因此他们必须侦听不同的端口,如下所示:
服务器
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Server {
void run() throws Exception {
DatagramSocket ds = new DatagramSocket(9999);
byte [] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
String msg = new String(dp.getData(),0,dp.getLength(),"UTF-8");
System.out.println("Message from client:" + msg);
//giving back to client
String str = "HI!, from server.";
byte[] b2 = str.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dop = new DatagramPacket(b2, b2.length, ia, 9998);
ds.send(dop);
System.out.println("Message sent back");
ds.close();
}
public static void main(String args[]) throws Exception {
Server server = new Server();
server.run();
}
}
和客户
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Client {
public static void main (String args[]) throws Exception {
DatagramSocket s = new DatagramSocket(9998);
String msg = "Hello! ,from client. ";
byte[] b = msg.getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(b, b.length, ia, 9999);
s.send(dp);
byte[] b2 = new byte[1024]; //byte array
DatagramPacket dip = new DatagramPacket(b2, b2.length);
s.receive(dip);
String str = new String(dip.getData(),0,dip.getLength(),"UTF-8");
System.out.println("From server" + str);
}
}