java

位置:IT落伍者 >> java >> 浏览文章

Java Socket编程UDP


发布日期:2018年06月29日
 
Java Socket编程UDP

看了下UDP编程的书写了个简单的例子代码如下

Java代码

import javaioIOException;

import DatagramPacket;

import DatagramSocket;

import InetAddress;

import SocketException;

public class UDPReceive {

public static void main(String[] args) {

Integer port = ;

byte[] buffer = new byte[];

try {

DatagramSocket datagramSocket = new DatagramSocket(port);

DatagramPacket datagramPacket = new DatagramPacket(buffer

bufferlength);

try {

for (;;) {

Systemoutprintln(begin receive data);

datagramSocketreceive(datagramPacket);

Systemoutprintln(datagramPacketgetAddress()getAddress()toString()+=======+new String(datagramPacketgetData()));

datagramPacketsetLength(datagramPacketgetData()toString()length());

}

} catch (IOException e) {

eprintStackTrace();

}

} catch (SocketException e) {

eprintStackTrace();

}

}

}

这个类用来接受消息

Java代码

import javaioIOException;

import DatagramPacket;

import DatagramSocket;

import InetAddress;

import SocketException;

import UnknownHostException;

public class UDPSend {

public static void main(String[] args) {

try {

for (;;) {

DatagramSocket sendSocket = new DatagramSocket();

DatagramPacket dataPack = new DatagramPacket(

hello welcome to study javagetBytes()

hello welcome to study javalength() InetAddress

getByName() new Integer());

try {

sendSocketsend(dataPack);

sendSocketclose();

} catch (IOException e) {

eprintStackTrace();

}

}

} catch (SocketException e) {

eprintStackTrace();

} catch (UnknownHostException e) {

eprintStackTrace();

}

}

}

这个类用来发送消息

               

上一篇:用java生成缩略图和给图上打上公司logo

下一篇:用Java编写简单的UDP网络通信程序