-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUDPClient.java
More file actions
executable file
·69 lines (61 loc) · 2.14 KB
/
Copy pathUDPClient.java
File metadata and controls
executable file
·69 lines (61 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package socketudp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
*
* @author Har
*/
public class UDPClient {
private int remotePort;
private InetAddress remoteIP;
private DatagramSocket socket; //UDP套接字
public UDPClient(String ip, String port) throws IOException {
this.remotePort = Integer.parseInt(port);
this.remoteIP = InetAddress.getByName(ip);
//创建一个UDP套接字,与本地任意一个未使用的UDP端口绑定
socket = new DatagramSocket();
//与本地一个固定的UDP端口绑定
//socket=new DatagramSocket(9000);
}
//定义一个数据的发送方法。
public void send(String msg) {
try {
//先准备一个待发送的数据报
byte[] outputData = msg.getBytes("GB2312");
//构建一个数据报文。
DatagramPacket outputPacket = new DatagramPacket(outputData,
outputData.length, remoteIP, remotePort);
//给UDPServer发送数据报
socket.send(outputPacket); //给UDPServer发送数据报
} catch (IOException ex) {
}
}
//定义一个数据的接收方法。
public String receive() {//throws IOException{
String msg;
//先准备一个空数据报文
DatagramPacket inputPacket = new DatagramPacket(new byte[512], 512);
try {
//阻塞语句,有数据就装包,以装完或装满为此.
socket.receive(inputPacket);
//从报文中取出字节数据并装饰成字符。
msg = new String(inputPacket.getData(),
0, inputPacket.getLength(), "GB2312");
} catch (IOException ex) {
msg = null;
}
return msg;
}
public void close() {
if (socket != null) {
socket.close();//释放本地端口.
}
}
}