黑马程序员技术交流社区
标题:
【黑马程序员】网络编程UDP数据传输
[打印本页]
作者:
huburt
时间:
2016-5-23 12:00
标题:
【黑马程序员】网络编程UDP数据传输
package exercise_internet;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class SendAndReceive {
public static void main(String[] args) {
// 开启线程用于接收消息
new Thread() {
public void run() {
try {
receive();
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
// 主线程发送消息
try {
send();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void send() throws Exception {
System.out.println("send执行");
DatagramSocket socket = new DatagramSocket();
Scanner sc = new Scanner(System.in);
while (true) {
String line = sc.nextLine();
DatagramPacket packet = new DatagramPacket(line.getBytes(), line.getBytes().length,
InetAddress.getByName("127.0.0.1"), 6666);
socket.send(packet);
if (line.equals("quit")) {
break;
}
}
socket.close();
System.out.println("send结束");
}
public static void receive() throws Exception {
System.out.println("receive执行");
DatagramSocket socket = new DatagramSocket(6666);
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
while (true) {
socket.receive(packet);
byte[] b = packet.getData();
int len = packet.getLength();
String ip = packet.getAddress().getHostAddress();
int port = packet.getPort();
String line = new String(b, 0, len);
if (line.equals("quit")) {
break;
}
System.out.println(ip + ":" + port + ":" + line);
}
socket.close();
System.out.println("receive结束");
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2