网络编程(2)UDP

TCP和UDP

☆ UDP     (DatagramSocket和DatagramPacket类)

    1.将数据及源和目的封装成数据包中,不需要建立连接
    2.每个数据报的大小在限制在64k内
    3.因无连接,是不可靠协议
    4.不需要建立连接,速度快

☆ TCP      (Socket 和  ServerSocket类)

    1.建立连接,形成传输数据的通道。
    2.在连接中进行大数据量传输
    3.通过三次握手完成连接,是可靠协议
    4.必须建立连接,效率会稍低

☆ Socket

    1.Socket就是为网络服务提供的一种机制。
    2.通信的两端都有Socket。
    3.网络通信其实就是Socket间的通信。
    4.数据在两个Socket间通过IO传输。

UDP传输

    •DatagramSocket与DatagramPacket
    •建立发送端,接收端。
    •建立数据包。
    •调用Socket的发送接收方法。
    •关闭Socket。

发送端与接收端是两个独立的运行程序。

UDP传输编程

☆发送端

在发送端,要在数据包对象中明确目的地IP及端口。

<span style="font-family:Times New Roman;font-size:14px;">//DatagramSocket用于通讯,  DatagramPacket数据包裹--发的 (包含数据)  
 //※要点:DatagramSocket类中的-----send(DatagramPacket p)方法</span>
<span style="font-family:Times New Roman;font-size:14px;">//1 new一个DatagramSocket对象</span>
<span style="font-family:Times New Roman;font-size:14px;">DatagramSocket ds = new DatagramSocket();//可以不指定端口,因为可以由系统随便给我们找个端口发出去就行了---端口是必须要有的,只是由系统自动给我们分配
</span>
<span style="font-family:Times New Roman;font-size:14px;">//3准备要发送包裹(要标明ip+端口)
byte[] by = “hello,udp”.getBytes();

DatagramPacketdp = new DatagramPacket(by,0,by.length,

  InetAddress.getByName(“127.0.0.1”),10000);
</span>
<span style="font-family:Times New Roman;font-size:14px;"> //2 发送包裹
ds.send(dp);

ds.close();

</span>


 

☆接收端

在接收端,要指定监听的端口。

<span style="font-family:Times New Roman;font-size:14px;">//DatagramSocket用于通讯,  DatagramPacket数据包裹--接的 (空的) 
 //※要点:DatagramSocket类中的-----receive(DatagramPacket p)方法</span>
<span style="font-family:Times New Roman;font-size:14px;">//1 new一个DatagramSocket对象</span>
<span style="font-family:Times New Roman;font-size:14px;">DatagramSocket ds = new DatagramSocket(10000);
</span>
<span style="font-family:Times New Roman;font-size:14px;">//3准备用于接收数据的包裹(要字节数组)
byte[] by = new byte[1024];

DatagramPacketdp = new DatagramPacket(by,by.length);

//2 接收包裹</span>
<span style="font-family:Times New Roman;font-size:14px;">ds.receive(dp);//阻塞方法

//4解析数据--解析包裹</span>
<span style="font-family:Times New Roman;font-size:14px;">String str = new String(dp.getData(),0,dp.getLength());

System.out.println(str+"--"+dp.getAddress());

ds.close();

</span>


 

练习:UDP聊天程序

    •通过键盘录入获取要发送的信息。
    •将发送和接收分别封装到两个线程中。

代码实现:

one:

<span style="font-family:Times New Roman;font-size:14px;">package cn.hncu.net.url.udpChat.one;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
 * 说明:在MyEclipse控制台中执行时,若想中文聊天无乱码,得把MyEclipse的默认编码设成:GBK
 */

public class UDPChat {

	public static void main(String[] args) {
		try {
			DatagramSocket dsSend = new DatagramSocket(10001);
			DatagramSocket dsRece = new DatagramSocket(10002);
			
			new Thread( new Send(dsSend) ).start();
			new Thread( new Receive(dsRece) ).start();
			
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
}

class Send implements Runnable{
	private DatagramSocket ds;
	public Send(DatagramSocket ds){
		this.ds = ds;
	}
	@Override
	public void run() {
		try {
			//源 System.in
			BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
			String line = null;
			while( (line=br.readLine())!=null){
				byte bs[] = line.getBytes("gbk");
				//目的 socket upd-package
				DatagramPacket dp = new DatagramPacket(bs, bs.length, InetAddress.getByName("127.0.0.1"),10004);
				ds.send(dp);
				if("over".equals(line)){// line.equals("over")
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}

class Receive implements Runnable{
	private DatagramSocket ds;
	public Receive(DatagramSocket ds){
		this.ds = ds;
	}
	@Override
	public void run() {
		try {
			while (true) {
				//源 socket -- ds.receive(dp)
				byte buf[] = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				ds.receive(dp);
				String ip = dp.getAddress().getHostName();
				String text = new String(dp.getData(), 0, dp.getLength(),"gbk");
				//目的 System.out
				System.out.println(ip+":"+ text);
				if("over".equals(text)){
					System.out.println(ip+"离开聊天室...");
					//break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}
</span>


two:

<span style="font-family:Times New Roman;font-size:14px;">package cn.hncu.net.url.udpChat.two;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPChat {

	public static void main(String[] args) {
		try {
			DatagramSocket dsSend = new DatagramSocket(10003);
			DatagramSocket dsRece = new DatagramSocket(10004);
			
			new Thread( new Send(dsSend) ).start();
			new Thread( new Receive(dsRece) ).start();
			
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
}

class Send implements Runnable{
	private DatagramSocket ds;
	public Send(DatagramSocket ds){
		this.ds = ds;
	}
	@Override
	public void run() {
		try {
			//源 System.in
			BufferedReader br = new BufferedReader( new InputStreamReader(System.in));
			String line = null;
			while( (line=br.readLine())!=null){
				byte bs[] = line.getBytes("gbk");
				//目的 socket upd-package
				DatagramPacket dp = new DatagramPacket(bs, bs.length, InetAddress.getByName("127.0.0.1"),10002);
				ds.send(dp);
				if("over".equals(line)){// line.equals("over")
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}

class Receive implements Runnable{
	private DatagramSocket ds;
	public Receive(DatagramSocket ds){
		this.ds = ds;
	}
	@Override
	public void run() {
		try {
			while (true) {
				//源 socket -- ds.receive(dp)
				byte buf[] = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				ds.receive(dp);
				String ip = dp.getAddress().getHostName();
				String text = new String(dp.getData(), 0, dp.getLength(),"gbk");
				//目的 System.out
				System.out.println(ip+":"+ text);
				if("over".equals(text)){
					System.out.println(ip+"离开聊天室...");
					//break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
}
</span>


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值