zoukankan      html  css  js  c++  java
  • JavaUDP,接收方接收发送方的数据(单向)

    Send(发送方):

    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 SendDemo1 {
    
    	private static final int PORT = 8080;
    	private static final String IP = "localhost";
    	public static void main(String[] args) {
    		sendHandler();
    	}
    
    	private static void sendHandler(){
    		DatagramSocket sendSocket = null;
    		try {
    			while(true){
    				//创建套接字
    				sendSocket = new DatagramSocket();
    				//键盘录入
    				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    				String send = br.readLine();
    				byte[] buf = send.getBytes();
    				//设定数据包内容,长度,发送到的地址和端口
    				DatagramPacket dp = new DatagramPacket(buf, buf.length, InetAddress.getByName(IP), PORT);
    				//发送数据包
    				sendSocket.send(dp);
    			}
    		} catch (SocketException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}finally{
    			if(sendSocket != null){
    				sendSocket.close();
    			}
    		}
    	}
    }
    


     


     

    Receive(接收方):

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.SocketException;
    
    
    public class ReceiverDemo1 {
    	
    	private static final int PORT = 8080;
    	public static void main(String[] args) {
    		receiveHandler();
    	}
    
    	private static void receiveHandler() {
    		DatagramSocket receiveSocket = null;
    		try {
    			//在8080端口监听
    			receiveSocket = new DatagramSocket(PORT);
    			//while循环,一直在等待接收数据
    			while(true){
    				//创建一个包,并接收数据
    				byte[] buf = new byte[1024];
    				DatagramPacket dp = new DatagramPacket(buf, buf.length);
    				receiveSocket.receive(dp);
    				
    				//取得IP地址和包里的数据内容
    				String ip = dp.getAddress().getHostAddress();
    				String data = new String(dp.getData(), 0, dp.getLength());
    				
    				System.out.println(ip + ":" + data);
    			}
    		} catch (SocketException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}finally{
    			if(receiveSocket != null){
    				receiveSocket.close();
    			}
    		}
    	}
    }
    


    先启动接收方,再启动发送方

  • 相关阅读:
    .net core ELK
    mongodb基础
    .net core FluentValidation
    使用Identity Server 4建立Authorization Server
    .net core JWT应用
    .net core action过滤器的普通应用
    matplotlib
    python-13:文件操作 之二
    python-13:文件操作 open
    python-12:内置 函数之一 filter map sorted reduce
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/2999574.html
Copyright © 2011-2022 走看看