UDP和TCP网络通信
关键三要素:
IP:设备在网络中的地址
端口:应用程序在设备中唯一的标识
协议:连接和数据在网络中传输的规则
1.InetAddress的常用方法
//获取本机Ip,以InetAddress对象返回InetAddress localHost = InetAddress.getLocalHost();System.out.println(localHost);//根据IP地址,返回InetAddress对象System.out.println(InetAddress.getByName("localhost"));//获取IP地址对象对应的主机名System.out.println(localHost.getHostName());//指定在毫秒内,判断主机与该IP对应的主机是否接通System.out.println(localHost.isReachable(2345));
2.UDP通信
public class Server {public static void main(String[] args)throws Exception {System.out.println("欢迎使用服务端");//创建服务端DatagramSocket socket=new DatagramSocket(6666);//创建数据包byte[]buffer=new byte[1024*60];DatagramPacket packet=new DatagramPacket(buffer, buffer.length);//接收信息while (true) {socket.receive(packet);//解码数据int length = packet.getLength();String s=new String(buffer,0,length);System.out.println(s);System.out.println("客户端IP地址:" + packet.getAddress().getHostAddress());//拿到客户端IP地址System.out.println("客户端端口:"+ packet.getPort());//拿到客户端端口System.out.println("欢迎下次使用");}}}public class Client {public static void main(String[] args) throws Exception {//创建客户端DatagramSocket socket=new DatagramSocket();//创建数据包Scanner sc=new Scanner(System.in);while (true) {System.out.println("请说:");String s = sc.nextLine();if ("exit".equals(s)){System.out.println("退出系统");socket.close();break;}byte[] buffer = s.getBytes();//创建发出去的数据包对象DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getLocalHost(), 6666);//发送数据包socket.send(packet);System.out.println("客户端已发送信息");}}}//多发多收//将接收,发送的内容使用死循环,服务端无需关闭//创建多个客户端(有循环的条件下)
注意事项:
先启动服务端,再启动客户端
3.TCP通信
public class Server2 {public static void main(String[] args) throws Exception{System.out.println("欢迎进入服务端");//创建服务端ServerSocket socket=new ServerSocket(6666);//创建数据包连接数据Socket accept = socket.accept();//创建字节输入流对象InputStream inputStream = accept.getInputStream();DataInputStream dis=new DataInputStream(inputStream);//接收数据while (true) {try {String s= dis.readUTF();System.out.println(s);} catch (IOException e) {System.out.println(accept.getRemoteSocketAddress()+"离线");dis.close();accept.close();socket.close();break;}}}}public class Client2 {public static void main(String[] args) throws Exception{//创建客户端System.out.println(InetAddress.getLocalHost());Socket socket=new Socket("10.4.136.23",6666);//创建字节输出流对象OutputStream outputStream = socket.getOutputStream();DataOutputStream dos=new DataOutputStream(outputStream);//发送内容Scanner sc=new Scanner(System.in);while (true) {System.out.println("请说:");String s = sc.nextLine();if ("exit".equals(s)){System.out.println("退出系统");socket.close();break;}dos.writeUTF(s);//刷新dos.flush();}}}
注意事项:
当有多个客户端时,只有一个客户端会和服务端连通
4.UDP与TCP的区别
UDP:无连接,不可靠通信,通信效率高------语音,视频通话
TCP:面向连接,可靠通信,通信效率低-----支付,下载