您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 商业计划书 > java编写的简单局域网聊天室(适合初学者)
importjava.awt.BorderLayout;importjava.awt.Button;importjava.awt.Color;importjava.awt.Dimension;importjava.awt.Font;importjava.awt.Frame;importjava.awt.Panel;importjava.awt.Point;importjava.awt.TextArea;importjava.awt.TextField;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.KeyAdapter;importjava.awt.event.KeyEvent;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.File;importjava.io.FileWriter;importjava.io.IOException;importjava.net.DatagramPacket;importjava.net.DatagramSocket;importjava.net.InetAddress;importjava.text.SimpleDateFormat;importjava.util.Date;importjava.util.Scanner;importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantLock;publicclassGUI_ChatextendsFrame{privatestaticfinallongserialVersionUID=1L;privateTextAreaviewTextArea=newTextArea(20,1);privateTextAreasendTextArea=newTextArea();privateTextFieldipTextField=newTextField(20);privateButtonsendButton=newButton(发送);privateButtonclearButton=newButton(清屏);privateButtonlogButton=newButton(记录);privateButtonshakeButton=newButton(震动);privatePanelpanel=newPanel();privateDatagramSocketsocket;privateLocklock=newReentrantLock();privateFileWriterfw;publicGUI_Chat()throwsException{socket=newDatagramSocket(20000);fw=newFileWriter(log.txt,true);generateUI();addListener();newReceiveThread().start();//开启接收数据的线程}privatevoidgenerateUI(){setTitle(GUI聊天室);setSize(400,600);setLocation(600,50);setMinimumSize(newDimension(400,600));//设置最小尺寸Fontfont=newFont(CourierNew,Font.PLAIN,15);viewTextArea.setFont(font);//设置字体viewTextArea.setEditable(false);//设置不可编辑(会改变背景色)viewTextArea.setBackground(Color.WHITE);//设置背景色add(viewTextArea,BorderLayout.NORTH);//把viewTextArea放在上面sendTextArea.setFont(font);add(sendTextArea,BorderLayout.CENTER);//把sendTextArea放在中间panel.add(ipTextField);panel.add(sendButton);panel.add(clearButton);panel.add(logButton);panel.add(shakeButton);add(panel,BorderLayout.SOUTH);//把Panel放在下面}privatevoidaddListener(){addWindowListener(newWindowAdapter(){//关闭窗体publicvoidwindowClosing(WindowEvente){try{fw.close();}catch(IOExceptione1){e1.printStackTrace();}System.exit(0);}});sendButton.addActionListener(newActionListener(){//发送功能publicvoidactionPerformed(ActionEvente){send();}});sendTextArea.addKeyListener(newKeyAdapter(){//处理快捷键publicvoidkeyPressed(KeyEvente){if(e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_ENTER||e.isAltDown()&&e.getKeyCode()==KeyEvent.VK_S){send();e.consume();//取消当前事件}}});clearButton.addActionListener(newActionListener(){//清屏功能publicvoidactionPerformed(ActionEvente){viewTextArea.setText();}});logButton.addActionListener(newActionListener(){//聊天记录publicvoidactionPerformed(ActionEvente){showLog();}});shakeButton.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){sendShake();}});}privatevoidsendShake(){try{Stringip=ipTextField.getText();sendData(ip,newbyte[]{-1});//向执行IP发送一个特殊的消息}catch(Exceptione){e.printStackTrace();}}privatevoidshowLog(){try(Scannerscanner=newScanner(newFile(log.txt));){viewTextArea.setText();//清屏fw.flush();//把未保存的数据写入文件while(scanner.hasNextLine())//如过文件中有数据就进入循环viewTextArea.append(scanner.nextLine()+\r\n);//从文件读取一行,追加到viewTextArea中}catch(Exceptione){e.printStackTrace();}}privatevoidsend(){try{Stringmsg=sendTextArea.getText();//获取要发的内容Stringip=ipTextField.getText();//获取目标地址ip=ip.trim().length()==0?255.255.255.255:ip;Stringcontent=getTime()+我对+(ip.equals(255.255.255.255)?所有人:ip)+说:\r\n+msg+\r\n\r\n;lock.lock();//开始同步sendData(ip,msg.getBytes());//发送数据sendTextArea.setText();//清空viewTextArea.append(content);//把要显示的内容追加到viewTextArea中fw.write(content);//保存聊天记录lock.unlock();//结束同步}catch(Exceptione){e.printStackTrace();}}privatevoidsendData(Stringip,byte[]data)throwsException{DatagramPacketpacket=newDatagramPacket(data,data.length,InetAddress.getByName(ip),20000);socket.send(packet);//UDP发送数据}privateStringgetTime(){Datedate=newDate();SimpleDateFormatsdf=newSimpleDateFormat(yyyy-MM-ddHH:mm:ss);returnsdf.format(date);//返回当前时间字符串}privateclassReceiveThreadextendsThread{publicvoidrun(){DatagramPacketpacket=newDatagramPacket(newbyte[8192],8192);while(true){try{socket.receive(packet);byte[]arr=packet.getData();intlength=packet.getLength();Strings=newString(arr,0,length);//接收到的字符串Stringip=packet.getAddress().getHostAddress();Stringcontent=getTime()++ip+对我说:\r\n+s+\r\n\r\n;//在viewTextArea中显示的内容if(length==1&&arr[0]==-1){//判断是否收到震动消息doShake();//震动(改变位置)continue;//进入下一次循环}lock.lock();//开始同步viewTextArea.append(content);fw.write(content);//保存聊天记录lock.unlock();//结束同步}catch(IOExceptione){e.printStackTrace();}}}}privatevoiddoShake(){//震动方法(通过改变窗体的位置实现)try{Pointpoint=getLocation();for(inti=0;i5;i++){Thread.sleep(30);setLocation(point.x+5,point.y);Thread.sleep(30);setLocation(point.x-5,point.y+5);}setLocation(point);}catch(InterruptedExceptione){e.printStackTrace();}}publicstaticvoidmain(String[]args)throwsException{newGUI_Chat().setVisible(true);}}
本文标题:java编写的简单局域网聊天室(适合初学者)
链接地址:https://www.777doc.com/doc-4219134 .html