udpagent.java

来自「自己写的」· Java 代码 · 共 40 行

JAVA
40
字号

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPAgent{

	DatagramSocket ds;
 	DatagramPacket rec;
 	byte[] buffer = new byte[1024];
 	
 	public static void main(String[] args) throws Exception {
 		UDPAgent agent = new UDPAgent();
  		agent.start();
 	}
 	
 	public void start() throws Exception {
 		
  		ds = new DatagramSocket(2008);
  		rec = new DatagramPacket(buffer,1024);
  		int count=0;
  		String[] rep = new String[2];
  		while(true){
  			try {
  				if(count==2){
  					//分别发送给两台机子
  					
  					return;
  				}
  				ds.receive(rec);
  				count = count +1;
  				rep[count-1] = count+":"+rec.getSocketAddress();
  				System.out.println(rep[count-1]);
  			} 
  			catch (Exception e) {
  				e.printStackTrace();
  			}
  		}
 	}
 	
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?