{网络编程}和{多线程}应用:基于UDP协议【实现多发送方发送数据到同一个接收者】--练习

要求:

使用多线程实现多发送方发送数据到同一个接收者

代码:

发送端:可以在多台电脑上启动发送端,同时向接收端发送数据

注意:匹配地址和端口号
package com.qf.demo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException; public class SendTest {
public static void main(String[] args) {
System.out.println("发送端已启动!"); DatagramSocket socket=null; try {
//1.创建socket对象
socket=new DatagramSocket();
//2.要发送的内容,可以用Scanner在后台输入
String string="最近很烦,有时间陪我聊天吗?";
DatagramPacket packet=new DatagramPacket(string.getBytes(), string.getBytes().length, InetAddress.getLocalHost(), 6677);
//3.发送数据
socket.send(packet);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(socket!=null){
socket.close();
}
}
}
}

接收端:

package com.qf.demo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException; public class ReceiveTest { public static void main(String[] args) {
// 1 socket try {
DatagramSocket socket = new DatagramSocket(6677);
while(true){
byte[] bs = new byte[1024];
DatagramPacket p = new DatagramPacket(bs, bs.length);
socket.receive(p);// 阻塞程序程序执行
MyThread thread = new MyThread(p);
thread.start();
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
} class MyThread extends Thread{
DatagramPacket p = null;
public MyThread(DatagramPacket p ) {
this.p = p;
}
@Override
public void run() { // 将接收到的数据进行 打印输出
System.out.println("接收到的--发送端--数据:"+new String(p.getData(),0,p.getLength()));
}
}

运行结果:

接收端:

{网络编程}和{多线程}应用:基于UDP协议【实现多发送方发送数据到同一个接收者】--练习

上一篇:Linux系统挂载新磁盘


下一篇:SpringMVC参数自动绑定