📄 datagramadditionclient.java
字号:
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
public class DatagramAdditionClient {
private InetAddress host;
private int port;
static final int DEFAULT_PORT=8189;
public DatagramAdditionClient(InetAddress host,int port){
this.host=host;
this.port=port;
}
public void run(){
try{
DatagramSocket client=new DatagramSocket();//创建数据报套接字,没有提供服务器地址和端口是因为
//已经放在了DatagramPacket对象中
String words="hello,Sever!"; //String对象中定义了要发送到服务器端的数据
DatagramPacket outDgp=new DatagramPacket(words.getBytes(),words.length(),host,port);
client.send(outDgp); //服务器地址和端口放在了DatagramPacket对象中
System.out.println("已经发送了"+words);
byte[] buffer=new byte[256]; /*为准备接受响应创建缓冲区和他的长度为构造函数参数的
输入DatagramPacket对象,然后使用与用于发送数据报相同的套接字接收响应数据报*/
DatagramPacket inDgp=new DatagramPacket(buffer,buffer.length);
client.receive(inDgp);
String rsp=new String(inDgp.getData(),0,inDgp.getLength());
System.out.println(rsp); //从输入数据中析取响应,并存入String对象中,响应被写入控制台
String quit=""; //当收到空字符串和他的长度放入输出对象DatagramPacket中,并发送
outDgp.setData(quit.getBytes());
outDgp.setLength(quit.length());
client.send(outDgp);
client.close(); //发送最后Datagram对象后,关闭套接字
}catch(IOException iox){
System.out.println(iox);
iox.printStackTrace();
}
}
public static void main(String[] args) {
try{
InetAddress host=InetAddress.getLocalHost();
int port=DEFAULT_PORT;
if(args.length>0){
port=Integer.parseInt(args[0]);
}
if(args.length>1){
host=InetAddress.getByName(args[1]);
}
DatagramAdditionClient addClient=new DatagramAdditionClient(host,port);
addClient.run();
}catch(UnknownHostException unx){
System.out.println(unx);
unx.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -