java udp socket实例

客户端:
package udp;

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 SimpleClient {

private DatagramSocket socket; // udp套接字
DatagramPacket packet = null;// udp数据包

public static void main(String[] args) {
SimpleClient client = new SimpleClient();
try {
client.connect();
client.send();
client.disconnect();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

private void disconnect() {

socket.close();
}

private void send() throws IOException {

byte[] buf = new String("UDP TEST data from client").getBytes(); //创建发送数据缓冲区
// 数据包包括所有的信息,ip地址,端口号及要发送的数据
DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress
.getByName("localhost"), 8888);

// 发送请求
System.out.println("serverPort = " + 8888);
socket.send(packet);
System.out.println("packet.getData()=" + new String(packet.getData()));
}
private void connect() throws SocketException { //创建连接

socket = new DatagramSocket();
}

}

服务器端:
package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class SimpleServer {
DatagramSocket socket; // udp套接字
DatagramPacket packet = null;// udp数据包

public static void main(String[] args) {

SimpleServer server = new SimpleServer();
try {
server.connect(8888); //连接
server.accept(); //接收请求
server.disconnect(); //关闭套接字
} catch (IOException e) {
e.printStackTrace();
}
}

private void disconnect() {
socket.close();
}

private void accept() throws IOException {

reveive();
}

private void reveive() throws IOException {
// 默认缓冲区大小,如果设置的缓冲区大小小于客户端发送的数据大小,怎么办??
byte[] buf = new byte[25];
packet = new DatagramPacket(buf, buf.length);

// 接收请求
socket.receive(packet);
System.out
.println("Received package = " + new String(packet.getData()));
}

private void connect(int port) throws SocketException { // 创建连接

socket = new DatagramSocket(port);
socket.setReceiveBufferSize(512);

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值