聊天室

初版

image-20231130230603737

发送端

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
import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class demol26 {
public static void main(String[] args) throws IOException {
DatagramSocket ds=new DatagramSocket();
Scanner sc=new Scanner(System.in);
while (true){
System.out.println("输入你要发的内容:");
String s=sc.nextLine();
if ("886".equals(s)){
break;
}
byte[] bytes = s.getBytes();
InetAddress sd=InetAddress.getByName("127.0.0.1");
int port=10086;
DatagramPacket dp=new DatagramPacket(bytes,bytes.length,sd,port);
ds.send(dp);
}
ds.close();

}
}

接收端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class demol27 {
public static void main(String[] args) throws IOException {
DatagramSocket si=new DatagramSocket(10086);
byte[]d=new byte[122];
DatagramPacket sd=new DatagramPacket(d,d.length);
while (true){
si.receive(sd);
byte[] e = sd.getData();
int len=sd.getLength();
String name = sd.getAddress().getHostName();
System.out.println(name+"发送了:"+new String(e,0,len));
}

}
}

注意:必须先运行接收端,程序员摸鱼必备,在同一个公网IP下都可以聊

更新于

请我喝[茶]~( ̄▽ ̄)~*

罗梓丰 微信支付

微信支付

罗梓丰 支付宝

支付宝