谁帮我写一个简单的JAVA程序,任务是用UDP写,请大手帮忙写一个思路~写个思路! 10
展开全部
给个例子你:
这是服务器端的:
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPServer {
public static void main(String[] args) {
DatagramSocket server = null;
DatagramPacket out =null;
DatagramPacket in = null;
try {
server = new DatagramSocket(6666);
// 接收
byte[] buff = new byte[256];
in = new DatagramPacket(buff, buff.length);
server.receive(in);
System.out.println(new String(buff));
// 发送
byte[] res = new Date().toString().getBytes("GBK");
out = new DatagramPacket(res, res.length, in.getSocketAddress());
server.send(out);
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是客户端的:
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPClient {
public static void main(String[] args) {
DatagramSocket client = null;
DatagramPacket out =null;
DatagramPacket in = null;
try {
client = new DatagramSocket();
// 要发送的消息(根据自己需要修改)
byte[] res = "Please give me your time!".getBytes("GBK");
out = new DatagramPacket(res, res.length, new InetSocketAddress("localhost", 6666));
client.send(out);
// 接收
byte[] buff = new byte[256];
in = new DatagramPacket(buff, buff.length);
client.receive(in);
System.out.println(new String(buff));
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
先运行服务器端再运行客户端
这是服务器端的:
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPServer {
public static void main(String[] args) {
DatagramSocket server = null;
DatagramPacket out =null;
DatagramPacket in = null;
try {
server = new DatagramSocket(6666);
// 接收
byte[] buff = new byte[256];
in = new DatagramPacket(buff, buff.length);
server.receive(in);
System.out.println(new String(buff));
// 发送
byte[] res = new Date().toString().getBytes("GBK");
out = new DatagramPacket(res, res.length, in.getSocketAddress());
server.send(out);
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是客户端的:
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPClient {
public static void main(String[] args) {
DatagramSocket client = null;
DatagramPacket out =null;
DatagramPacket in = null;
try {
client = new DatagramSocket();
// 要发送的消息(根据自己需要修改)
byte[] res = "Please give me your time!".getBytes("GBK");
out = new DatagramPacket(res, res.length, new InetSocketAddress("localhost", 6666));
client.send(out);
// 接收
byte[] buff = new byte[256];
in = new DatagramPacket(buff, buff.length);
client.receive(in);
System.out.println(new String(buff));
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
先运行服务器端再运行客户端
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询