版权声明:前半生,不害怕;后半生,不后悔! https://blog.csdn.net/qq_14842117/article/details/89257879
网络编程三要素:
1.IP地址
2.端口
3.协议
InetAddress --获取IP对象类
InetAddress address = InetAddress.getByName("主机名或者ip地址");
address.getHostName();//获取主机名
address.getHostAddress();//获取IP地址
1.UDP协议发送接收数据数据
//UDP协议发送数据
public class UDPsend {
public static void main(String[] args) throws IOException {
//1.创建发送端Socket对象
DatagramSocket ds = new DatagramSocket();//This class represents a socket for sending and receiving datagram packets.
//2.创建数据,并把数据打包
//DatagramPacket(byte[] buf,int length,InetAddress address,int port)构造一个数据报包,用于将长度为length的数据包发送到指定主机上指定的端口号。
//创建数据
byte[] bys = "hello,world".getBytes();
int length = bys.length;
InetAddress address = InetAddress.getByName("10.173.54.56");
//端口
int port = 10086;
DatagramPacket dp = new DatagramPacket(bys,length,address,port);
//调用Socket对象的发送方法发送数据包
//public void send(DatagramPacket p)
ds.send(dp);
//释放资源
ds.close();
}
}
//UDP协议接收数据
public class UDPreceive {
public static void main(String[] args) throws IOException{
//创建接收端Socket对象
//DategramSocket(int port)
DatagramSocket ds = new DatagramSocket(10086);
//创建一个数据包(接收容器)
//DatagramPacket(byte[] buf,int length)
byte [] bys = new byte[1024];
int length = bys.length;
DatagramPacket dp = new DatagramPacket(bys,length);
//调用Socket对象的接收方法接收数据
//publicvoid receive(DatagramPacket p)
ds.receive(dp);//阻塞式方法
//解析数据包,并显示在控制台
//获取对方的ip
//public InetAddress getAddress()
InetAddress address = dp.getAddress();
String ip = address.getHostAddress();
//public byte[] getData()://获取数据缓冲区
//public int getLength():获取数据实际长度
byte [] bys2 = dp.getData();
int len = dp.getLength();
String s = new String(bys2,0,len);
System.out.println(ip+":"+s);
//释放资源
ds.close();
}
}
2.TCP发送接收数据
注意:一定要先开启服务器端,因为tcp保证数据一定能收到。
public class TCPsend {
public static void main(String[] args) throws UnknownHostException, IOException {
//创建发送端的Socket对象
Socket s = new Socket("10.173.54.56",8888);
//获取输出流,写数据
//public OutputStream getOutputStream()
OutputStream os = s.getOutputStream();
os.write("hello,tcp".getBytes());
s.close();
}
}
public class TCPreceive {
//1.创建接收端的Socket对象
//2.监听客户端连接,返回一个Socket对象
//3.获取输出流,读数据,显示在控制台
//4.释放资源
public static void main(String[] args) throws IOException {
//创建接收端的Socket对象
ServerSocket ss = new ServerSocket(8888);
//监听客户端,返回一个对应的Socket对象
//public Socket accept
Socket s = ss.accept();//侦听并接受到此套接字的连接。此方法在连接传入之前一直阻塞
//获取输入流,读取显示在控制台
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys);//阻塞式方法
String str = new String(bys,0,len);
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip+"---"+str);
//释放资源
s.close();
//ss.close()这个不应该关闭
}
}