UDP
是一种不可靠的传输协议,发送之前不需要建立连接,且发送的数据,发送方也不需要知道对方是否接收到,容易导致数据的流失
1、发送端的建立
1>建立udp的Socket服务,如果不明确端口,会自动分配一个端口
2>明确要发送的数据;按字节传输
3>将数据封装成数据包;Datagram(Byte[],int length,InetAddress,int port)
4>代码实现:
import java.net.*;
class UDPSender
{
public static void main(String[] args)
{
//建立接口的连接
DatagramSocket sender=new DatagramSocket(8888);
//数据
String text="hehhe";
Byte[] bud=text.getBytes();
//封装成包
DatagramPacket DGP=new DatagramPacket(bud,bud.length,InetAdderess.getByName("www.baidu.com"),8888);
//发送
DGP.send();
//销毁
DGP.close()
}
}
2.、接收端的建立
1>创建端口的连接,并且明确接口,只有发送至该接口的数据才会被接收;
2>定义数据包,用于接收并存储数据;
3>接收到的数据存到上面定义的数据包中;
4>通过数据包的方法去获取包中的特定信息;
5>关闭资源;
6>代码实现。
class UDPRece
{
public static void main(String[] args)
{
DatagramSocket DSR=new DatagramSocket("1000");
Bytep[] buf=new Byte[1024];
DatagramPacket DP=new DatagramPacket(buf,buf.length);
ds.receive(DP);
//udp数据包中只有传输方的ip,并没有主机名称,通过扩区ip来获取主机名称。
String ip=DP.getAddress().getHostName();
int port=dp.getPort();
//udp数据包中有数据和数据的长度的参数
String text=new String(DP.getData(),0,DP.getLength());
System.out.println("ip:"+ip+" "+"port:"+port+" "+"数据:"+text);
DP.close();
}
}
TCP
通过三次握手建立起客户端和服务端的连接,是可靠的数据传输协议。
代码实现:
class TcpServer
{
public static void main(String[] args)
{
//服务端先建立起服务,并一直监听某端口
ServerSocket as=new ServerSocket(10002);
Socket s=ss.accept();//获取客户端对象
//Socket的方法,用套接字去获取网络名称,继而获得地址
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+".....connected");
InputStream in=s.getInputStream();
Byte[] buf=new Byte[1024];
int len=in.read(buf);
String text=new String(buf,0,len);
System.out.println(text);
s.close();
ss.close();
}
}