#项目实现相关# | windows、Java | UDP收发数据、TCP收发数据简单例程

项目场景:

运行环境:windows10笔记本、win10台式、TCP&UDP调试助手、IDEA。

实现描述:

  • 需求:通过UDP发送数据后,持续地进行TCP协议格式的数据接收。
  • 问题:不知道怎么保持UDP发送数据后,等到TCP收到数据再停止发送广播包。
  • 解决思路:通过两个线程?但是并未很好的解决。

实现过程:

一、Windows环境下传感器设备数据收发的简单环境测试。

1、UDP发送数据。

package com.record.medicalterminal;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * ClassName:UDPServer
 * package:com.record.medicalterminal
 * Description:
 * 实现UDP的客户端功能。发送数据给UDP服务器端。
 * UDP协议接收数据:
 * A:创建发送端Socket对象
 * B:创建一个数据包(发送容器)
 * C:调用Socket对象的发送方法接收数据
 * E:释放资源
 * @Date:2021/10/26 UDPServer
 */
public class UDPServer {
	public static void main(String[] args) throws IOException {
		// 创建发送端Socket对象
		DatagramSocket ds = new DatagramSocket();

		// 创建一个数据包(发送容器)
		String dataSendCommand = "3001092000830000ffff000000000000";
		byte[] bys = dataSendCommand.getBytes();
		int length = bys.length;
		int port = 10086;
		String ipAddress = "127.0.0.1";
//		String ipAddress = "192.168.50.125";
//		String ipAddress = "255.255.255.255";
		InetAddress address = InetAddress.getByName(ipAddress);
		DatagramPacket dp = new DatagramPacket(bys, length, address, port);

		// 调用Socket对象的发送方法接收数据
		int i = 5;
		while(i-- > 0){
			ds.send(dp);
			System.out.println("UDPserver向" + address + "发送了:" + new String(bys));
		}

		// 释放资源
		ds.close();
	}
}

2、UDP接收数据

package com.record.medicalterminal;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * ClassName:UDPClient
 * package:com.record.medicalterminal
 * Description:
 *	UDP协议接收数据:
 * A:创建接收端Socket对象
 * B:创建一个数据包(接收容器)
 * C:调用Socket对象的接收方法接收数据
 * D:解析数据包,并显示在控制台
 * E:释放资源
 * @Date:2021/10/26 UDPClient
 */
public class UDPClient {
	public static void main(String[] args) throws IOException {
		// 创建接收端Socket对象
		DatagramSocket ds = new DatagramSocket(10086);

		// 创建一个数据包(接收容器)
		byte[] bys = new byte[1024];
		int length = bys.length;
		DatagramPacket dp = new DatagramPacket(bys, length);

		// 调用Socket对象的接收方法接收数据
//		int i = 1;
		while(true){
			ds.receive(dp);					// 阻塞方法
System.out.println(dp.getAddress().getHostAddress());
		}
	}
}

3、TCP接收数据

package com.record.medicalterminal;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * ClassName:TCPServer
 * package:com.record.medicalterminal
 * Description:
 * 单次接收数据
 * @Date:2021/10/26 TCPServer
 */
public class TCPServer {
	public static void main(String[] args) throws IOException {
		// 创建接收端的套接字对象
		ServerSocket ss = new ServerSocket(8888);
		// 监听客户端连接,返回相应的Socket对象
		Socket s = ss.accept();
		// 获取输入流对象,从输入流中获取数据
		InputStream is = s.getInputStream();
		byte[] bys = new byte[1024];
		int len = is.read(bys);
		String str = new String(bys, 0, len);
		System.out.println("From Client" + "(" + s.getInetAddress().getHostAddress() + "):" + str);
		// 释放资源
		s.close();
	}
}

4、TCP发送请求数据

package com.record.medicalterminal;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * ClassName:TCPClient
 * package:com.record.medicalterminal
 * Description:
 * TCP协议的客户端,用来向服务器发送请求,接收返回的消息并显示
 * @Date:2021/10/26 TCPClient
 */
public class TCPClient {
	public static void main(String[] args) throws IOException {
//		String ipAddress = "127.0.0.1";
		String ipAddress = "192.168.50.125";
		// 创建Socket套接字对象
		Socket s = new Socket(ipAddress, 8888);
		// 获取输出流对象,写数据
		OutputStream os = s.getOutputStream();
		String outData = "hello,世界";
		os.write(outData.getBytes());
		System.out.println("send " + outData + " to " + ipAddress + " success!");
		Scanner sc = new Scanner(System.in);
		while (true){
			os.write(sc.nextLine().getBytes());
			if(sc.nextLine().equals("q")){
				break;
			}
			sc.nextLine();
		}
		// 释放资源
		s.close();
	}
}

5、线程发1送UDP数据,线程2接收TCP数据

package com.record.medicalterminal;

import java.io.IOException;
import java.io.InputStream;
import java.net.*;

public class UDPServerTCPClient {
	public static void main(String[] args) throws IOException {
		RunnableDemo R1 = new RunnableDemo( "Thread-1");
		R1.start();

		RunnableDemoTCPServer R3 = new RunnableDemoTCPServer("Thread-3");
		R3.start();
	}
}

/**
 * 实现UDP数据单次发送
 */
class RunnableDemo implements Runnable {
	private Thread t;
	private String threadName;

	RunnableDemo( String name) {
		threadName = name;
		System.out.println("Creating " +  threadName );
	}

	public void run() {
		System.out.println("Running " +  threadName );
		try {
			for(int i = 4; i > 0; i--) {
				System.out.println("Thread: " + threadName + ", " + i);
				// 让线程睡眠一会
				Thread.sleep(50);
			}

			//下面是自己编写的UDP发送数据的程序
			// 创建发送端Socket对象
			DatagramSocket ds = new DatagramSocket();

			// 创建一个数据包(发送容器)
			String dataSendCommand = "3001092000830000ffff000000000000";
			byte[] bys = dataSendCommand.getBytes();
			int length = bys.length;
			int port = 10086;
//			String ipAddress = "127.0.0.1";
			String ipAddress = "192.168.50.125";
//			String ipAddress = "255.255.255.255";
			InetAddress address = InetAddress.getByName(ipAddress);
			DatagramPacket dp = new DatagramPacket(bys, length, address, port);

			// 调用Socket对象的发送方法接收数据
			int i = 5;
			while(i-- > 0){
				ds.send(dp);
				System.out.println("UDPserver向" + address + "发送了:" + new String(bys));
			}

			// 释放资源
			ds.close();

		}catch (InterruptedException e) {
			System.out.println("Thread " +  threadName + " interrupted.");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Thread " +  threadName + " exiting.");
	}

	public void start () {
		System.out.println("Starting " +  threadName );
		if (t == null) {
			t = new Thread (this, threadName);
			t.start ();
		}
	}
}

/**
 * 实现TCP数据持续的接收
 */
class RunnableDemoTCPServer implements Runnable {
	private Thread t;
	private String threadName;

	RunnableDemoTCPServer( String name) {
		threadName = name;
		System.out.println("Creating " +  threadName );
	}

	public void run() {
		System.out.println("Running " +  threadName );
		try {
			for(int i = 4; i > 0; i--) {
				System.out.println("Thread: " + threadName + ", " + i);
				// 让线程睡眠一会
				Thread.sleep(50);
			}


			// 创建接收端的套接字对象
			ServerSocket ss = new ServerSocket(8888);
			// 监听客户端连接,返回相应的Socket对象
			Socket s = ss.accept();

			// 获取输入流对象,从输入流中获取数据
			while (true){
				InputStream is = s.getInputStream();
				byte[] bys = new byte[1024];
				int len = is.read(bys);
				String str = new String(bys, 0, len);
				System.out.println("From Client" + "(" + s.getInetAddress().getHostAddress() + "):" + str);

				if(str.equals("q")){
					break;
				}
			}

			// 释放资源
			s.close();

		}catch (InterruptedException e) {
			System.out.println("Thread " +  threadName + " interrupted.");
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Thread " +  threadName + " exiting.");
	}

	public void start () {
		System.out.println("Starting " +  threadName );
		if (t == null) {
			t = new Thread (this, threadName);
			t.start ();
		}
	}
}

6、成功实现两线程wait/notify 简单通信

package com.record.medicalterminal;
import java.util.ArrayList;
import java.util.List;
/**
 * ClassName:ThreadLockDemo1
 * package:com.record.medicalterminal
 * Description:
 * 两个线程通过wait/ notify 进行通信
 * @Date:2021/11/5 ThreadLockDemo1
 */
public class ThreadLockDemo1 {
	public static void main(String[] args) {

		try {
			Object lock = new Object();

			ThreadA a = new ThreadA(lock);
			a.start();

			Thread.sleep(50);

			ThreadB b = new ThreadB(lock);
			b.start();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class MyList {

	private static List<String> list = new ArrayList<String>();

	public static void add() {
		list.add("anyString");
	}

	public static int size() {
		return list.size();
	}
}


class ThreadA extends Thread {

	private Object lock;

	public ThreadA(Object lock) {
		super();
		this.lock = lock;
	}

	@Override
	public void run() {
		try {
			synchronized (lock) {
				if (MyList.size() != 5) {
					System.out.println("wait begin "
							+ System.currentTimeMillis());
					lock.wait();
					System.out.println("wait end  "
							+ System.currentTimeMillis());
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}


class ThreadB extends Thread {
	private Object lock;

	public ThreadB(Object lock) {
		super();
		this.lock = lock;
	}

	@Override
	public void run() {
		try {
			synchronized (lock) {
				for (int i = 0; i < 10; i++) {
					MyList.add();
					if (MyList.size() == 5) {
						lock.notify();
						System.out.println("已经发出了通知");
					}
					System.out.println("添加了" + (i + 1) + "个元素!");
					Thread.sleep(1000);
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

7、TCP接收数据,通过notify唤醒UDP

package com.record.medicalterminal;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
/**
 * ClassName:ThreadLockDemo1
 * package:com.record.medicalterminal
 * Description:
 * 两个线程通过wait/ notify 进行通信
 * @Date:2021/11/5 ThreadLockDemo1
 */
public class ThreadLockDemo1 {
	public static void main(String[] args) {

		try {
			Object lock = new Object();

			ThreadA a = new ThreadA(lock);
			a.start();

			Thread.sleep(50);

			ThreadB b = new ThreadB(lock);
			b.start();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class MyList {

	private static List<String> list = new ArrayList<String>();

	public static void add() {
		list.add("anyString");
	}

	public static int size() {
		return list.size();
	}
}


class ThreadA extends Thread {

	private Object lock;

	public ThreadA(Object lock) {
		super();
		this.lock = lock;
	}

	@Override
	public void run() {
		try {
			synchronized (lock) {
				if (MyList.size() != 5) {
					System.out.println("wait begin "
							+ System.currentTimeMillis());

					// 创建发送端Socket对象
					DatagramSocket ds = new DatagramSocket();
					// 创建一个数据包(发送容器)
					String dataSendCommand = "3001092000830000ffff000000000000";
					byte[] bys = dataSendCommand.getBytes();
					int length = bys.length;
					int port = 10086;
		//			String ipAddress = "127.0.0.1";
		//			String ipAddress = "192.168.50.125";
					String ipAddress = "255.255.255.255";
					InetAddress address = InetAddress.getByName(ipAddress);
					DatagramPacket dp = new DatagramPacket(bys, length, address, port);
					// 调用Socket对象的发送方法接收数据
					int i = 10, k = 0;
					while(i -- > 0){
						ds.send(dp);
						System.out.println("UDPserver向" + address + "发送 " + new String(bys) + " " + (k++) + " 次");
						Thread.sleep(1000);
					}

					lock.wait();
					System.out.println("wait end  "
							+ System.currentTimeMillis());
					// 释放资源
					ds.close();
				}
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


class ThreadB extends Thread {
	private Object lock;

	public ThreadB(Object lock) {
		super();
		this.lock = lock;
	}

	@Override
	public void run() {
		try {
			synchronized (lock) {
				// 创建接收端的套接字对象
				ServerSocket ss = new ServerSocket(8888);
				// 监听客户端连接,返回相应的Socket对象
				Socket s = ss.accept();
				// 获取输入流对象,从输入流中获取数据
				int i = 0;
				while (true){
					InputStream is = s.getInputStream();
					byte[] bys = new byte[1024];

					int len = is.read(bys);
					if(len != 0 && ++i == 1){
						lock.notify();
					}

					String str = new String(bys, 0, len);
					System.out.println("From Client" + "(" + s.getInetAddress().getHostAddress() + ") " + "i=" + i + " :" + str);
					if(str.equals("q")){
						break;
					}
				}

				System.out.println("已经发出了通知");
				// 释放资源
				s.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值