tcp与udp区别:
- 基于连接与无连接
- 对系统资源的要求(TCP较多,UDP少)
- UDP程序结构较简单
- 流模式与数据报模式
TCP保证数据正确性,UDP可能丢包
TCP 保证数据顺序,UDP不保证
java编程区别:
tcp是java.net.ServerSocket(用于服务器端)和java.net.Socket(用于客户端);
UDP是java.net.DatagramSocket.
UDP程序例子
发送程序:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpSend {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "hello , world!";
DatagramPacket dp = new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("192.168.0.105"),3000);
ds.send(dp);
ds.close(); //关闭连接
}
}
接收程序:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpRecv {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
String str = new String(dp.getData(),0,dp.getLength());
System.out.println(str);
System.out.println("IP:" + dp.getAddress().getHostAddress() + ",PORT:" + dp.getPort());
ds.close();
}
}
c语言编程区别:
- socket() 的参数不同
- UDP Server不需要调用listen和accept
- UDP收发数据用 sendto/recvfrom函数
- TCP:地址信息在connect/accept时确定
UDP:在 sendto/recvfrom函数中每次均 需指定地址信息 - UDP:shutdown函数无效