网络编程UDP

 

 

 

 

网络编程UDP

 

 

网络通讯要素

1.找到对方的IP

2.数据要发送到对方指定的应用程序上,为了标识这些应用程序,所以给这些网络应用程序都用数字进行标识,为了方便称呼这个数字,叫做端口,逻辑端口。

tomcat默认8080,

3.定义通信规则。这个通信规则称为协议,国际组织定义了TCP/IP

 

 

IP地址:InetAddress

网络中设备的标识

不易记忆,可用主机名

本地回环地址:127.0.0.1  主机名:localhost

端口号

用于标识进程的逻辑地址,不同进程的标识

有效端口:0~65535,其中0~1024系统使用或保留端口。

传输协议

通讯的规则常见协议:TCP,UDP

 

import java.net.*;

class  IPDemo
{
	public static void main(String[] args) throws Exception
	{
		//获取本地主机
		InetAddress i = InetAddress.getLocalHost();

		System.out.println(i.toString());//打印主机名和地址
		System.out.println("address:"+i.getHostAddress());//打印地址
		System.out.println("name:"+i.getHostName());//打印主机名

		//获取任意一个主机的地址getByName参数可以是地址也可以是主机名。
		//如果该方法如果没有找到与参数对应的主机名,那么还是输出该地址。
		InetAddress ia = InetAddress.getByName("thinkpad-sl400");
		System.out.println("address:"+ia.getHostAddress());
		System.out.println("name:"+ia.getHostName());

	//一般使用中以IP地址为主,因为主机名还需要进行解析
	}
}

 

 

 

TCP和UDP

UDP

1.将数据及源和目的封装成数据包中,不需要建立连接

2.每个数据报的大小在限制在64k内

3.因无连接,是不可靠协议

4.不需要建立连接,速度快

一般使用与聊天工具,视频会议,桌面共享等。

TCP

1.建立连接,形成传输数据的通道。

2.在连接中进行大数据量传输

3.通过三次握手完成连接,是可靠协议

4.必须建立连接,效率会稍低

应用于电话,下载等。

 

Socket

Socket就是为网络服务提供的一种机制。

通信的两端都有Socket。

网络通信其实就是Socket间的通信。

数据在两个Socket间通过IO传输。

 

 

需求:通过udp传输方式,将一段文字数据发送出去。,

定义一个udp发送端。

思路:

1,建立updsocket服务。

2,提供数据,并将数据封装到数据包中。

3,通过socket服务的发送功能,将数据包发出去。

4,关闭资源。

 

import java.net.*;
class  UdpSend
{
	public static void main(String[] args) throws Exception
	{
		//1,创建udp服务。通过DatagramSocket对象。
		DatagramSocket ds = new DatagramSocket(8888);

		//2,确定数据,并封装成数据包。DatagramPacket(byte[] buf, int length, InetAddress address, int port) 

		byte[] buf = "udp ge men lai le ".getBytes();
		DatagramPacket dp = 
			new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.254"),10000);

		//3,通过socket服务,将已有的数据包发送出去。通过send方法。
		ds.send(dp);

		//4,关闭资源。

		ds.close();

	}
}

 

 

需求:

定义一个应用程序,用于接收udp协议传输的数据并处理的。

 

定义udp的接收端。

思路:

1,定义udpsocket服务。通常会监听一个端口。其实就是给这个接收网络应用程序定义数字标识。

方便于明确哪些数据过来该应用程序可以处理。

 

2,定义一个数据包,因为要存储接收到的字节数据。

因为数据包对象中有更多功能可以提取字节数据中的不同数据信息。

3,通过socket服务的receive方法将收到的数据存入已定义好的数据包中。

4,通过数据包对象的特有功能。将这些不同的数据取出。打印在控制台上。

5,关闭资源。

 

class  UdpRece
{
	public static void main(String[] args) throws Exception
	{
		//1,创建udp socket,建立端点。建立端口的语句放到循环外面
		DatagramSocket ds = new DatagramSocket(10000);
		while(true)
		{
		//2,定义数据包。用于存储数据。
		byte[] buf = new byte[1024];
		DatagramPacket dp = new DatagramPacket(buf,buf.length);

		//3,通过服务的receive方法将收到数据存入数据包中。
		ds.receive(dp);//阻塞式方法。
		

		//4,通过数据包的方法获取其中的数据。
		String ip = dp.getAddress().getHostAddress();

		String data = new String(dp.getData(),0,dp.getLength());

		int port = dp.getPort();

		System.out.println(ip+"::"+data+"::"+port);

		}
		//5,关闭资源
		//ds.close();
	}
}

 

 

import java.net.*;
import java.io.*;
class  UdpSend2
{
	public static void main(String[] args) throws Exception
	{
		//建立socket对象
		DatagramSocket ds = new DatagramSocket();
		//接收键盘录入
		BufferedReader bufr = 
			new BufferedReader(new InputStreamReader(System.in));

		String line = null;
		//读取流中的数据
		while((line=bufr.readLine())!=null)
		{
			if("886".equals(line))
				break;

			byte[] buf = line.getBytes();
			//将数据封装成数据包
			DatagramPacket dp = 
				new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10001);//定义为数组内容全部输出,主机名,端口

			ds.send(dp);
		}
		ds.close();
	}
}



class  UdpRece2
{
	public static void main(String[] args) throws Exception
	{
		DatagramSocket ds = new DatagramSocket(10001);

		while(true)
		{
			byte[] buf = new byte[1024];
			DatagramPacket dp = new DatagramPacket(buf,buf.length);

			ds.receive(dp);

			String ip = dp.getAddress().getHostAddress();
			String data = new String(dp.getData(),0,dp.getLength());
			

			System.out.println(ip+"::"+data);
		}
	}
}

 

 

编写一个聊天程序。

有收数据的部分,和发数据的部分。

这两部分需要同时执行。

那就需要用到多线程技术。

一个线程控制收,一个线程控制发。

 

因为收和发动作是不一致的,所以要定义两个run方法。

而且这两个方法要封装到不同的类中。

 

import java.io.*;
import java.net.*;
class Send implements Runnable
{
	private DatagramSocket ds;
	public Send(DatagramSocket ds)
	{
		this.ds = ds;
	}
	public void run()
	{
		try
		{
			BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
			String line = null;

			while((line=bufr.readLine())!=null)
			{
				byte[] buf = line.getBytes();

				DatagramPacket dp = 
					new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10002);

				ds.send(dp);

				if("886".equals(line))
					break;
			}
		}
		catch (Exception e)
		{
			throw new RuntimeException("发送端失败");
		}
	}
}

class Rece implements Runnable
{

	private DatagramSocket ds;
	public Rece(DatagramSocket ds)
	{
		this.ds = ds;
	}
	public void run()
	{
		try
		{
			while(true)
			{
				byte[] buf = new byte[1024];
				DatagramPacket dp = new DatagramPacket(buf,buf.length);

				ds.receive(dp);


				String ip = dp.getAddress().getHostAddress();

				String data = new String(dp.getData(),0,dp.getLength());

				if("886".equals(data))
				{
					System.out.println(ip+"....离开聊天室");
					break;
				}


				System.out.println(ip+":"+data);
			}
		}
		catch (Exception e)
		{
			throw new RuntimeException("接收端失败");
		}
	}
}


class  ChatDemo
{
	public static void main(String[] args) throws Exception
	{
		DatagramSocket sendSocket = new DatagramSocket();
		DatagramSocket receSocket = new DatagramSocket(10002);

		new Thread(new Send(sendSocket)).start();
		new Thread(new Rece(receSocket)).start();

	}
}

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值