UDP聊天室:循环的发送字
通过while循环,文字一直可以发送
dp.getData()是获取 **DatagramPacket**中存储的数据的字节数组。
发送端:
java
package TseUDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
public class LoginCelint {
//客户端
public static void main(String[] args) {
System.out.println("我是客户端---------------");
//发送信息
Scanner scanner = new Scanner(System.in);
DatagramPacket dp = null;
DatagramSocket ds = null;
try {
while (true){
System.out.print("客户端请输入:");
String msg = scanner.nextLine();
dp = new DatagramPacket(msg.getBytes(),
msg.getBytes().length,
InetAddress.getByName("127.0.0.1"),
8888);
ds = new DatagramSocket();
ds.send(dp);
//接收
byte b[] = new byte[100];
dp = new DatagramPacket(b,b.length);
ds.receive(dp);
String content = new String(dp.getData());
System.out.println("服务器说"+content);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
ds.close();
}
}
}
接收端:
java
package TseUDP;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.util.Scanner;
public class LoginServer {
//服务器
public static void main(String[] args) {
System.out.println("我是服务端------------------------------");
Scanner scanner = new Scanner(System.in);
DatagramPacket dp = null;
DatagramSocket ds = null;
try {
ds = new DatagramSocket(8888);
while (true) {
byte b[] = new byte[100];
dp = new DatagramPacket(b, b.length);
//等待接收
ds.receive(dp);
//拆包
String msg = new String(dp.getData());
System.out.println("客户端对我说:" + msg);
//发送
System.out.print("服务器请输入:");
String content = scanner.next();
//发送地址:获得上个数据包的发送地址
SocketAddress sa = dp.getSocketAddress();
dp = new DatagramPacket(content.getBytes(),
content.getBytes().length,
sa);
ds.send(dp);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
ds.close();
}
}
}