import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.*; public class UDP { public static void main(String[] args) { DatagramSocket datagramSocket = null; try { datagramSocket = new DatagramSocket(); InetAddress inetAddress = InetAddress.getByName("127.0.0.1"); int port = 9090; byte[] bytes = "我是发送端".getBytes("utf-8"); DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,inetAddress,port); datagramSocket.send(datagramPacket); } catch (SocketException e) { throw new RuntimeException(e); } catch (UnknownHostException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { if (datagramSocket != null) { datagramSocket.close(); } } } @Test public void Receiver() { try { int port = 9090; DatagramSocket datagramSocket = new DatagramSocket(port); byte[] bytes = new byte[1024 * 64]; DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length); datagramSocket.receive(datagramPacket); System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength())); } catch (SocketException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
public class UDP
{
public static void main(String[] args)
{
DatagramSocket datagramSocket = null;
try
{
datagramSocket = new DatagramSocket();
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
int port = 9090;
byte[] bytes = "我是发送端".getBytes("utf-8");
DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,inetAddress,port);
datagramSocket.send(datagramPacket);
}
catch (SocketException e)
{
throw new RuntimeException(e);
}
catch (UnknownHostException e)
{
throw new RuntimeException(e);
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
finally
{
if (datagramSocket != null)
{
datagramSocket.close();
}
}
}
@Test
public void Receiver()
{
try
{
int port = 9090;
DatagramSocket datagramSocket = new DatagramSocket(port);
byte[] bytes = new byte[1024 * 64];
DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length);
datagramSocket.receive(datagramPacket);
System.out.println(new String(datagramPacket.getData(),0,datagramPacket.getLength()));
}
catch (SocketException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}文章来源地址https://www.toymoban.com/news/detail-607814.html
文章来源:https://www.toymoban.com/news/detail-607814.html
到了这里,关于计算机网络技术与JAVA网络编程UDP编程-----JAVA入门基础教程-----计算机网络经典的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!