1.udp的简述
UDP协议提供的服务不同于TCP协议的端到端服务,它是面向非连接的,属不可靠协议,UDP套接字在使用前不需要进行连接。
2.客户端代码,
DatagramSocket ds=new DatagramSocket(1086); byte[] bys = new byte[1024]; int len = bys.length; DatagramPacket dp = new DatagramPacket(bys, len); ds.receive(dp); byte[] by = dp.getData(); int length = dp.getLength(); InetAddress address = dp.getAddress(); String ip = address.getHostAddress(); String s = new String(by, 0, length); System.out.println(ip + "---" + s);ds.close();
3.服务端代码
DatagramSocket ds=new DatagramSocket(); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String line=null; byte [] bys=line.getBytes(); int num=bys.length; InetAddress address=InetAddress.getByName("172.19.106.2"); int port=1086; DatagramPacket dp=new DatagramPacket(bys,num, address,port); ds.send(dp); ds.close();
2.tcp的简述
CP协议提供面向连接的服务,通过它建立的是可靠地连接。
客户端
//1.创建对象 ServerSocket sk=new ServerSocket(11111); //2.监听 Socket s=sk.accept(); //打包数据 BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); BufferedReader bw=new BufferedReader(new InputStreamReader(System.in)); OutputStream os=s.getOutputStream(); String line=null; while((line=br.readLine())!=null){ System.out.println("Client \t"+line); os.write(bw.readLine().getBytes()); } //释放资源 s.close(); //sk.close();
服务端
Socket sk=new Socket("192.168.60.218",11111); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(sk.getOutputStream())); String line=null; while((line=br.readLine())!=null){ bw.write(line); bw.newLine(); bw.flush(); InputStream is=sk.getInputStream(); byte [] by=new byte[1024]; int num=is.read(by); String h=new String(by, 0, num); System.out.println("Service:\t"+h); } //br.close(); //bw.close(); sk.close();
后面还有呢,,,