关于UDP和TCP协议的区别

简单的区分可以概括为TCP传输更可靠,效率比UDP低,所以二者都有各自的应用场景。

在Java中,客户端的socket设置好服务端的IP和端口,组装好数据包,就可以直接向服务端

发送数据。下面是详细代码:

package com.Demo;
import java.net.DatagramPacket;
 import java.net.DatagramSocket;
 import java.net.InetAddress;
 import java.net.SocketException;
 import java.net.UnknownHostException;public class MyUdpClient {
     int port;
     InetAddress address = null;
     DatagramSocket socket = null;  //客户端socket
     DatagramPacket  data = null;  //数据包
     
     public MyUdpClient(int port,String IP){
         super();
         this.port = port;
         try {
             address = InetAddress.getByName(IP);
             System.out.println("UDP客户端已启动");
         } catch (UnknownHostException e) {
             // TODO 自动生成的 catch 块
             e.printStackTrace();
         }        
     }
     
     public void SendMsg(String msg){
         try {
             socket = new DatagramSocket();
             byte[] b = msg.getBytes();
             data = new DatagramPacket(b,b.length,this.address,this.port);
             socket.send(data);            
         } catch (Exception e) {
             // TODO 自动生成的 catch 块
             e.printStackTrace();
         }
     }
 }
  package com.Demo;
import java.util.Scanner;
public class UDPClientDemo {
    public static void main(String[] args) {
         // TODO 自动生成的方法存根
         MyUdpClient client = new MyUdpClient(8080,"192.168.1.101");
         Thread t = new Thread(new Runnable(){            @Override
             public void run() {
                 // TODO 自动生成的方法存根
                 while (true){
                     Scanner sc= new Scanner(System.in);
                     String st = sc.nextLine();//获取输入信息
                     client.SendMsg(st);
                 }
             }
             
         });
         t.start();
     }}