网络编程(UDP)

网络参考模型

网络通讯要素

  1. IP地址:网络中设备的标识
    本地回环地址:127.0.0.1 主机名:localhost
  2. 端口号:用于标识进程的逻辑地址,不同进程的标识
    有效端口:0~65535,其中0~1024系统使用或保留端口
  3. 传输协议:通讯的规则
    常见协议:UDP、TCP
  • UDP
    例:QQ、对讲机

    • 将数据及源和目的封装成数据包中,不需要建立连接
    • 每个数据包的大小限制在64k
    • 因无连接,是不可靠协议(可能找不到地址)
    • 不需要建立连接,速度快
  • TCP
    例:打电话

    • 建立连接,形成传输数据的通道。
    • 在连接中进行大数据量传输。
    • 通过三次握手完成连接,是可靠的
      A:B你在吗?
      B:我在
      A:我知道了
    • 必须建立连接,效率会降低

UDP传输

  • Socket(插座)
    相当于港口
    • 为网络服务提供的一种机制
    • 通信的两端都有Socket
    • 网络通信其实就是Socket间的通信
    • 数据在两个Socket间通过IO传输
  • UDP传输
    • DatagramSocket与DatagramPacket
    • 建立发送端,接收端
    • 建立数据包
    • 调用Socket的发送接收方法
    • 关闭Socket
      发送端与接收端是两个独立运行的程序

创建udp的发送端

思路:

  1. 建立udp的socket服务。
  2. 将要发送的数据封装到数据包中
  3. 通过udp的socket服务将数据包发送出去
  4. 关闭socket服务

代码演示

public class UDPSendDemo {
	
	public static void main(String[] args) throws IOException {
		System.out.println("发送端启动");
		
		//1.udpsocket服务。使用DatagramSocket对象
		DatagramSocket ds = new DatagramSocket();
		
		//2.将要发送的数据封装到数据包中
		String str = "udp传输演示:哥们来了";
			//使用DatagramPacket将数据封装到该对象包中。
		byte[] buf = str.getBytes();
		
		DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.101"),10000);
		
		//3.通过udp的socket服务将数据包发送出去.
		ds.send(dp);
		
		//4.关闭资源
		ds.close();
	}
}

创建udp的接收端

思路:

  1. 建立udp socket服务,因为是要接收数据,必须要明确一个端口号
  2. 创建数据包,用于存储接收到的数据。方便用数据包对象的方法解析这些数据
  3. 使用socket服务的receive方法将接收到的数据存储到数据包中
  4. 通过数据包中的方法解析数据包中的数据
  5. 关闭资源

代码演示

public class UDPReceiveDemo {

	public static void main(String[] args) throws IOException {
		
		System.out.println("接收端启动");
		
		//1.建立udp socket服务
		DatagramSocket ds = new DatagramSocket(10000);
		
		//2.创建数据包
		byte[] buf = new byte[1024];
		DatagramPacket dp = new DatagramPacket(buf,buf.length);
		
		//3.使用接收方法将数据存储到数据包中
		ds.receive(dp);//阻塞式的
		
		//4.通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。
		String ip = dp.getAddress().getHostAddress();
		int port = dp.getPort();
		String str = new String(dp.getData(),0,dp.getLength());
		
		System.out.println(ip+":"+port+":"+str);
		//5.关闭资源
		ds.close();
	}
}

制作一个聊天小程序

public class Chat {

	public static void main(String[] args) throws SocketException {
		DatagramSocket send = new DatagramSocket();
		DatagramSocket receive = new DatagramSocket(10000);
		
		new Thread(new Send(send)).start();
		new Thread(new Receive(receive)).start();
	}
}

class Send implements Runnable{

	DatagramSocket ds;

	public Send(DatagramSocket ds) {
		this.ds = ds;
	}

	public void run() {
		BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
		String line = null;
		try {
			while((line=bufr.readLine()) != null) {
				byte[] buf = line.getBytes();
				DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.101"),10000);
				ds.send(dp);
				if("886".equals(line))
					break;
			}
		} catch (IOException e) {
			e.printStackTrace();
			ds.close();
		}
		ds.close();	
	}
}

class Receive implements Runnable{
	DatagramSocket ds;

	public Receive(DatagramSocket ds) {
		this.ds = ds;
	}

	public void run() {

		while(true) {
			byte[] buf = new byte[1024];
			DatagramPacket dp = new DatagramPacket(buf,buf.length);
			
			try {
				ds.receive(dp);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			String ip = dp.getAddress().getHostAddress();
			int port = dp.getPort();
			String str = new String(dp.getData(),0,dp.getLength());
			if(str.equals("886")) {
				System.out.println(ip+":"+port+"退出了聊天室");
			}
			System.out.println(ip+":"+port+":"+str);
		}
	}
}

TCP传输

客户端建立的过程。

  1. 创建tcp客服端socket服务。使用的是Socket对象。
    建议改对象一创建就明确目的地。要连接的主机。
  2. 如果连接建立成功,说明数据传输通道已建立。
    该通道就是socket流,是底层建立好的。既然是流,说明这里既有输入,也有输出。
    想要输入或者输出流对象,可以找Socket来获取。
    可以通过getOutputStream(),和getInputStream()来获取两个字节流。
  3. 使用输出流,将数据写入。
  4. 关闭资源

** 代码演示 **

public class ClientDemo {
	public static void main(String[] args) throws UnknownHostException, IOException {

		//创建客服端socket服务。
		Socket socket = new Socket("192.168.0.101",10002);
		
		//获取socket流中的输出流
		OutputStream out = socket.getOutputStream();
		
		//使用输出流将指定的数据写出去
		out.write("tcp演示,哥们来了!".getBytes());
		
		//关闭资源
		socket.close();
	}
}

服务端建立的过程。

  1. 创建服务端socket对象,通过ServerSocket对象
  2. 服务端必须对外提供一个端口,否则客服端无法连接。
  3. 获取连接过来的客服端对象
  4. 通过客户端对象获取socket流读取客户端发过来的数据并打印到控制台上。
  5. 关闭资源。关客户端,关服务端。
    ** 代码演示 **
public class ServerDamo {

	public static void main(String[] args) throws IOException {
	//服务端接收客户端发送过来的数据,并打印到控制台上。	
		//1.创建服务端对象
		ServerSocket ss = new ServerSocket(10002);
		
		//2.获取连接过来的客服端对象
		Socket s = ss.accept();//阻塞式
		
		String ip = s.getInetAddress().getHostAddress();
		
		//3.通过socket对象获取输入流,要读取客户端发来的数据
		InputStream in = s.getInputStream();
		byte[] buf = new byte[1024];
		int len = in.read(buf);
		System.out.println(ip+":"+new String(buf,0,len));
		
		s.close();
		ss.close();
	}
}

猜你喜欢

转载自blog.csdn.net/cw13223/article/details/85058401