TCP和UDP同属于传输层协议
1.TCP和UDP的区别:
UDP协议
(1)将数据源和目的地封装到数据包中,不需要建立连接;
(2)每个数据包的大小限制最大64k;
(3)因为不建立连接,所以安全性差,速度快。
TCP协议
(1)建立连接形成传输数据的通道,然后再传输数据,通过三次的握手和四次挥手;
(2)安全性高,效率低;
2.UDP编程
(1)创建socket服务对象:
public void server(){ DatagramSocket ds = null; try { ds = new DatagramSocket(10000); //创建一个字节数组 byte[] bs = new byte[1024]; //创建数据包 DatagramPacket dp = new DatagramPacket(bs,bs.length); System.out.println("UDP服务已启动..."); //接收数据 ds.receive(dp); //获得客户端的ip InetAddress inetAddress = dp.getAddress(); //获得数据 byte[] data = dp.getData(); //获得数据的长度 int length = dp.getLength(); //创建接收的字符串 String str = new String(data,0,length); System.out.println(inetAddress.getAddress()+"发送的数据是:"+str); } catch (Exception e) { e.printStackTrace(); } finally { if(ds!=null){ ds.close(); } } }
(2)创建UDP客户对象:
public static void main(String[] args){ DatagramSocket ds = null; try { ds = new DatagramSocket(); String str = "Hellow!"; byte[] data = str.getBytes(); //创建数据包 DatagramPacket dp = new DatagramPacket(data,data.length, InetAddress.getByName("192.168.29.1"),10000); ds.send(dp); } catch (Exception e) { e.printStackTrace(); } finally { } }
3.TCP网络编程
(1)TCP服务端创建:
public static void main(String[] args){ ServerSocket ss = null; Socket s = null; BufferedReader reader = null; //创建服务端套接字 try { ss = new ServerSocket(9999); System.out.println("服务启动..."); //接收客户的请求 s = ss.accept(); //获取流对象 InputStream inputStream = s.getInputStream(); reader = new BufferedReader(new InputStreamReader(inputStream)); //读取数据 String line= reader.readLine(); InetAddress address = s.getInetAddress(); //获取客户端的ip地址 String ip = address.getHostAddress(); System.out.println(ip+"发送的数据为:"+line); } catch (IOException e) { e.printStackTrace(); }finally { try { if(reader!=null){ reader.close(); } if(s!=null){ s.close(); } if(ss!=null){ ss.close(); } } catch (IOException e) { e.printStackTrace(); } } }
(2)TCP客户端创建:
public static void main(String[] args){ //创建请求socket Socket s = null; BufferedWriter writer = null; try { s = new Socket("127.0.0.1",9999); //获得输出流 OutputStream out = s.getOutputStream(); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write("hellow!"); writer.newLine(); writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(writer!=null){ writer.close(); } if(s!=null){ s.close(); } } catch (IOException e) { e.printStackTrace(); } } }