——- android培训、java培训、期待与您交流! ———-
客户端发送请求,服务器端接收请求并做出相应
/**
*客户端
*/
public class AskClient {
public static void main(String []args){
while(true){
//1.确定发送给服务器的信息,服务器端地址以及端口
Scanner input = new Scanner(System.in);
System.out.println("我说:");
String mes = input.next();
byte[] a = mes.getBytes();
InetAddress ia = null;
try {
ia = InetAddress.getByName("localhost");
} catch (UnknownHostException e) {
e.printStackTrace();
}
int post = 8800;
//2.创建数据包,发送指定长度的信息到指定的服务器的指定端口
DatagramPacket dp = new DatagramPacket(a, a.length,ia,post);
//3.创建DatmSocket对象
DatagramSocket y = null;
try {
y = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//4.向服务器发送数据包
try {
y.send(dp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//接受服务器的响应
//2.确定接收方接受的数组的大小
byte[] buf = new byte[1314];
//3.创建接受类型的数据包,数据将存放在数组中
DatagramPacket dp2 = new DatagramPacket(buf, buf.length);
//4.通过套接字接受数据
try {
y.receive(dp2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//5.解析服务器的响应
String mess = new String(buf,0,dp.getLength());
System.out.println("服务器说:"+mess);
//5.释放资源
y.close();
}
}
}
/**
*服务器端
*/
public class AskServer {
public static void main(String[] args) {
try {
//1.创建接收方(服务器)套接字,并绑定端口号
DatagramSocket a = new DatagramSocket(8800);
//2.确定接收方接受的数组的大小
byte[] buf = new byte[1314];
//3.创建接受类型的数据包,数据将存放在数组中
DatagramPacket dp = new DatagramPacket(buf, buf.length);
//4.通过套接字接受数据
a.receive(dp);
//5.解析发送方发送的数据
String mess = new String(buf,0,dp.getLength());
System.out.println("客户端说:"+mess);
//响应客户端
Scanner input = new Scanner(System.in);
System.out.println("我说");
String reply = input.next();
byte[]replys = reply.getBytes();
//响应地址
SocketAddress sa = dp.getSocketAddress();
//数据包
DatagramPacket dp2 = new DatagramPacket(replys, replys.length,sa);
a.send(dp2);
//6.释放资源
a.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}