java,UDP实现聊天室功能
话不多说,先来看实现效果--------------------------------->
实现功能:(功能全部实现向指定ip发送)
一、界面搭建
public void init(){
this.setSize(500,600);
int windowWidth = this.getWidth(); //获得窗口宽
int windowHeight = this.getHeight(); //获得窗口高
Toolkit kit = Toolkit.getDefaultToolkit(); //定义工具包
Dimension screenSize = kit.getScreenSize(); //获取屏幕的尺寸
int screenWidth = screenSize.width; //获取屏幕的宽
int screenHeight = screenSize.height; //获取屏幕的高
this.setLocation(screenWidth/2-windowWidth/2, screenHeight/2-windowHeight/2);//设置窗口居中显示
new Receive().start();
//随机端口号
try {
socket = new DatagramSocket();
bw = new BufferedWriter(new FileWriter("config.txt",true)); //需要在尾部追加
} catch (Exception e) {
e.printStackTrace();
}
this.setVisible(true); //显示
}
public void centerPanel(){
Panel center = new Panel();
//创建显示的文本框
viewText = new TextArea();
//创建发送文本框
sendText = new TextArea(5,1);
center.setLayout(new BorderLayout()); //设置为边界布局管理器
center.add(viewText,BorderLayout.CENTER);
center.add(sendText,BorderLayout.SOUTH);
viewText.setEditable(false); //设置不可编辑
viewText.setBackground(Color.white); //设置背景色
viewText.setFont(new Font("xxx",Font.PLAIN,15)); //设置显示区字体
sendText.setFont(new Font("xxx",Font.PLAIN,15)); //设置发送区字体
this.add(center,BorderLayout.CENTER);
}
public void southPanel(){
Panel south = new Panel(); //创建南边的Panel
//创建文本字段,用来存储ip地址
tf = new TextField(20);
//设置默认ip
tf.setText("xxx.xxx.xxx.xxx");//注意:这里的xxx.xxx.xxx.xxx是默认的ip地址
//创建发送按钮
send = new Button("send");
//创建记录按钮
lg = new Button("record");
//创建清屏按钮
clear = new Button("clear");
//创建震动按钮
shock = new Button("shock");
south.add(tf);
south.add(send);
south.add(lg);
south.add(clear);
south.add(shock);
this.add(south,BorderLayout.SOUTH);
}
二、发送信息
private void send(byte[] arr,String ip) throws Exception{
DatagramPacket packet = new DatagramPacket(arr,arr.length, InetAddress.getByName(ip),9999);
socket.send(packet);
}
private void send() throws Exception{
String message = sendText.getText(); //创建发送区的内容
String ip = tf.getText(); //获取ip地址
ip = ip.trim().length() == 0 ? "255.255.255.255":ip;
send(message.getBytes(),ip);
//发送信息
String time = getCurrentTime();
str = time + "我对:" + (ip.equals("255.255.255.255") ? "所有人":ip) + "说:\r\n" + message + "\r\n";
viewText.append(str); //显示信息
bw.write(str); //将信息写到数据库中
sendText.setText(""); //发送后将发送区改为空
}
三、接收消息
private class Receive extends Thread{
public void run(){
try {
DatagramSocket socket = new DatagramSocket(9999);
DatagramPacket packet = new DatagramPacket(new byte[8192],8192);
while (true){
socket.receive(packet); //接收信息
byte[] arr = packet.getData(); //获取字节数据
int len = packet.getLength(); //获取有效的字节数据长度
if(arr[0] == -1 && len == 1){ //如果发过来的第一存储值是-1,并且数组长度是1
shock(); //调用震动动作
continue; //终止本次循环,进入下次循环
}
String message = new String(arr,0,len); //将有效的字节数据转换成字符串
String time = getCurrentTime();
String ip= packet.getAddress().getHostAddress();
str1 = time + " " + ip + "对我说:\r\n" + message + "\r\n";
viewText.append(str1);
bw.write(str1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
四、聊天记录
private void logFile() throws Exception{
bw.flush();
FileInputStream fis = new FileInputStream("config.txt");
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //在内存中创建缓冲区
int len;
byte[] arr = new byte[8192];
while((len=fis.read(arr))!=-1){
baos.write(arr,0,len);
}
String str = baos.toString(); //将内存中的内容转换成字符串
viewText.setText(str);
}
五、清楚屏幕
clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
viewText.setText("");
}
});
六、发送“抖一抖”
private void shock() {
int x = this.getLocation().x;
int y = this.getLocation().y;
try {
for (int i = 0; i < 10; i++) {
this.setLocation(x+20,y+20);
Thread.sleep(20);
this.setLocation(x+20,y-20);
Thread.sleep(20);
this.setLocation(x-20,y+20);
Thread.sleep(20);
this.setLocation(x-20,y-20);
Thread.sleep(20);
this.setLocation(x,y);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
七、快捷键
sendText.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) { //键盘快捷键操作
if(e.getKeyCode() == KeyEvent.VK_ENTER){ //Enter键快捷发送消息
try {
send();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});
文章里面只是部分功能代码,要查看全部代码,请戳这里下载! 下载全部代码
https://download.csdn.net/download/hwt1070359898/11074481