创建两个类 分别添加main方法 一个作为server类一个作为client类
客户端先发送再接收 服务器端先接收再发送
下面给你一个server和client的例子 你在基础上改一下就行了
client发送的时候发送三边值 server接收后 写一个计算三角形面积的函数 把接收到的三边值传入函数计算出结果作为数据返回到client端
/**
*UDPServer
*/
import java.io.*;
import java.net.*;
class UDPServer{
public static void main(String[] args)throws IOException{
DatagramSocket server = new DatagramSocket(5050);
byte[] recvBuf = new byte[100];
DatagramPacket recvPacket
= new DatagramPacket(recvBuf , recvBuf.length);
server.receive(recvPacket);
String recvStr = new String(recvPacket.getData() , 0 , recvPacket.getLength());
System.out.println("Hello World!" + recvStr);
int port = recvPacket.getPort();
InetAddress addr = recvPacket.getAddress();
String sendStr = "Hello ! I'm Server";
byte[] sendBuf;
sendBuf = sendStr.getBytes();
DatagramPacket sendPacket
= new DatagramPacket(sendBuf , sendBuf.length , addr , port );
server.send(sendPacket);
server.close();
}
}
/**
*UDPClient
*/
import java.io.*;
import java.net.*;
class UDPClient{
public static void main(String[] args)throws IOException{
DatagramSocket client = new DatagramSocket();
String sendStr = "Hello! I'm Client";
byte[] sendBuf;
sendBuf = sendStr.getBytes();
InetAddress addr = InetAddress.getByName("127.0.0.1");
int port = 5050;
DatagramPacket sendPacket
= new DatagramPacket(sendBuf ,sendBuf.length , addr , port);
client.send(sendPacket);
byte[] recvBuf = new byte[100];
DatagramPacket recvPacket
= new DatagramPacket(recvBuf , recvBuf.length);
client.receive(recvPacket);
String recvStr = new String(recvPacket.getData() , 0 ,recvPacket.getLength());
System.out.println("收到:" + recvStr);
client.close();
}
}