网络编程:
七层:应用层,表示层,回话层,传输层,网络层,数据链路层,物理层
四层:应用层,传输层,网络层,主机
UDP:
将数据及源和目的封装成数据包中,不需要建立连接
每个数据包的大小限制在64k
因为是无连接,是不可靠协议
不需要建立连接,速度快
TCP:
建立连接,形成传输数据的通道。
在连接中进行大数据量的传输
通过三次握手完成连接,是可靠协议
必须建立连接,效率会降低
网络通信三要素:IP地址,端口号,传输协议
创建UDP传输的发送端
1.建立udp的socket服务
2.将要发送的数据封装到数据包中
3.同过udp的socket服务将数据包发送出去
4.关闭socket服务
建立UDP接受端的思路
1.建立udp,socket服务
2.创建数据包,用于存储接收到的数据,方便用数据包对象的方法解析这些数据
3.使用socket服务的receive方法将接收到的数据存储到数据包中
4.使用数据包的方法解析数据包中的数据
5.关闭资源
程序:
发送端:
publicstatic void main(String[] args) throws IOException {
System.out.println("发送端启动");
//1.建立udp的socket服务
DatagramSocketds = new DatagramSocket();
//2.封装要发送的数据
Stringstr = "哥们来了";
byte[]buf = str.getBytes();
DatagramPacketdp = new DatagramPacket(buf, buf.length,InetAddress.getByName("10.17.64.86"), 10000);
//3.发送数据
ds.send(dp);
//4.关闭服务
ds.close();
}
接收端:
publicstatic void main(String[] args) throws IOException {
System.out.println("接收端启动........");
//1.建立udp,socket服务,必须绑定端口,接收从该端口发来的数据
DatagramSocket ds = new DatagramSocket(10000);
//2.创建数据包对象用来接收数据
byte[]buf = new byte[1024];
DatagramPacketdp = new DatagramPacket(buf, buf.length);
//3.使用receive方法,开始接收数据
ds.receive(dp);//阻塞状态
//4.解析数据包对象的内容
Stringip = dp.getAddress().getHostAddress();
intport = dp.getPort();
Stringcontent = new String(dp.getData());
System.out.println(ip+":"+port+":"+content);
}
多线程聊天室
publicclass TSendDemo implements Runnable{
privateDatagramSocket ds ;
publicTSendDemo(DatagramSocket ds) {
super();
this.ds= ds;
}
@Override
publicvoid run() {
System.out.println("发送端启动...........");
try{
BufferedReaderbufr = new BufferedReader(new InputStreamReader(System.in));
Stringstr = null;
while((str= bufr.readLine())!=null){
if("over".equals(str)){
System.out.println("退出聊天室");
break;
}
byte[]buf = str.getBytes();
DatagramPacketdp = new DatagramPacket(buf, buf.length,InetAddress.getByName("10.17.64.86"), 20000);
ds.send(dp);
}
}catch (Exception e) {
}
}
接收端
publicclass TReceiveDemo implements Runnable{
privateDatagramSocket ds ;
publicTReceiveDemo(DatagramSocket ds) {
super();
this.ds= ds;
}
@Override
publicvoid run() {
System.out.println("接收端启动...........");
try{
while(true){
byte[]buf = new byte[1024];
DatagramPacketdp = new DatagramPacket(buf, buf.length);
ds.receive(dp);
System.out.println(dp.getAddress().getHostAddress()+":"+newString(dp.getData(),0,dp.getLength()));
}
}catch (Exception e) {
//TODO: handle exception
}
}
测试
publicstatic void main(String[] args) throws SocketException {
DatagramSocketsendds = new DatagramSocket();
DatagramSocketreceiveds = new DatagramSocket(20000);
TSendDemosend = new TSendDemo(sendds);
TReceiveDemoreceive = new TReceiveDemo(receiveds);
newThread(send).start();
newThread(receive).start();
}