UDP的特点是速度快,不安全
UDP的控制台聊天实现的原理是一个发送端,一个接收端,发送端负责发送数据打包,接收端负责拆包,解析,我们用循环分别让发送端和接收端一直运行,并且通过线程让他们异步运行,这样,只要两台电脑上都有这个程序,并设置好端口号和IP,就可以实现控制台聊天了。
代码如下:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public
class
Talk {
// UDP????
public
static
void
main(
String[]
args)
throws
SocketException,
Exception {
// ??????????????
new
Thread(
new
Runnable() {
@Override
public
void
run() {
while (
true) {
try {
//本机的端口号设置为8888
DatagramSocket
ds =
new
DatagramSocket(
8888);
byte[]
buf =
new
byte[
1024];
int
length =
buf.
length;
DatagramPacket
dp =
new
DatagramPacket(buf, length);
ds.
receive(dp);
// 拆包
InetAddress
ip =
dp.
getAddress();
byte[]
data =
dp.
getData();
int
length1 =
dp.
getLength();
// 设置打印在控制台的格式
String
s1 =
new
String(data,
0, length1);
SimpleDateFormat
sdf =
new
SimpleDateFormat(
"HH:mm:ss");
String
time =
sdf.
format(
new
Date());
String
message =
dp.
getAddress().
getHostAddress()+time+
" "+s1;
System.
out.
println(message);
ds.
close();
}
catch (
SocketException
e) {
e.
printStackTrace();
}
catch (
IOException
e) {
e.
printStackTrace();
}
}
}
}).
start();
while (
true) {
//接收端
DatagramSocket
ds =
new
DatagramSocket();
// 键盘录入
Scanner
sc =
new
Scanner(
System.
in);
String
s =
sc.
nextLine();
SimpleDateFormat
sdf =
new
SimpleDateFormat(
"HH:mm:ss");
String
time =
sdf.
format(
new
Date());
String
message = time+
" "+s;
byte[]
bytes =
message.
getBytes();
int
len =
bytes.
length;
// 设置对面的端口号和IP,联机的时候需要根据对方电脑设置
InetAddress
ia =
InetAddress.
getByName(
"127.0.0.1");
int
port =
8888;
// 打包并发送
DatagramPacket
packet =
new
DatagramPacket(bytes, len, ia, port);
ds.
send(packet);
}
}
}