我一直告诫自己:要做一个踏实认真的人 E-mail:realoneyjw@ qq:18238423
像这种作业最好还是自己做
既然你也写了一个,那还是用你自己的最好,
努力吧
我也试了一下
客户端
import java.io.*;
import java.net.*;public class UDPtest {
public static void main(String []args){
DatagramSocket dp = null;
InetAddress address = null;
DatagramPacket packet = null;
if(args.length != 1)
{
System.out.println(\"Please use the command java UDPtest <hostname>\"); return; }
try {
dp = new DatagramSocket();
} catch (SocketException e) {
System.out.println(\"打开端口失败\");
}
byte[] data = new byte[256];
try {
address = InetAddress.getByName(args [0]);
} catch (UnknownHostException e) {
System.out.println(\"没有找到对方主机\");
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
data = br.readLine().getBytes();
packet = new DatagramPacket (data, data.length, address, 5000);
dp.send(packet);
packet = new DatagramPacket(data,data.length);
dp.receive(packet);
String received = new String(packet.getData(),0,packet.getLength());
while(!received.equals(\"bye\"))
{
System.out.println(received + \" from \"+address.getHostAddress()+\":\"+packet.getPort());
data = br.readLine().getBytes();
packet = new DatagramPacket (data, data.length, address, 5000);
dp.send(packet);
data = new byte[256];
packet = new DatagramPacket(data,data.length);
dp.receive(packet);
received = new String(packet.getData(),0,packet.getLength());
}
} catch (IOException e) {
e.printStackTrace();
}
dp.close();
}
}
import java.io.*;
import java.net.*;public class UDPserver {
public static void main(String []args){
DatagramSocket dp = null;
DatagramPacket packet = null;
try {
dp = new DatagramSocket(5000);
} catch (SocketException e) {
System.out.println(\"打开端口失败\");
}
byte[] data = new byte[256];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
packet = new DatagramPacket (data, data.length);
dp.receive(packet);
String received = new String(packet.getData(),0,packet.getLength());
while(!received.equals(\"bye\"))
{
InetAddress address = packet.getAddress();
int port = packet.getPort();
System.out.println(received + \" from \"+address.getHostAddress()+\":\"+port);
data = br.readLine().getBytes();
packet = new DatagramPacket(data,data.length,address,port);
dp.send(packet);
data = new byte[256];
packet = new DatagramPacket (data, data.length);
dp.receive(packet);
received = new String(packet.getData(),0,packet.getLength());
}
} catch (IOException e) {
e.printStackTrace();
}
dp.close();
}}