资源描述:
《java聊天工具作业报告》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、Java实验作业报告专业:学号:姓名:一、实验内容利用java实现简单的聊天平台。二、实验目的学习java网络编程的基础内容,了解TCP/IP协议的简单概念,和JAVA结合编程。三、实验分析1、建立服务器CServero2、建立客户端CCliento四、实现代码1.服务器Serverimportjava.io.*;importjava.net.*;importjava,awt.*;importjava,awt.event.*;importjavax.swing.*;publicclassServ
2、erextendsJFrame{JTextFieldjtf=newJTextField(30);JTextAreajta=newJTextAreaO;JButtonjb=newJButton("发送");JPaneljp=newJPanel();DatagramSocketserversocket=null;DatagramPacketserverpacket=null,serverpacketl=null;InetAddressaddress;intport;Stringdatagram;pu
3、blicServer(){jp-setLayout(newFlowLayout());jp.add(jtf);jp.add(jb);this.getContentPane().add(jp,BorderLayout.SOUTH);this,getContentPaneO.add(newJScrollPane(jta),BorderLayout.CENTER);jta.setEditable(false);jb.addActionListener(newbuttonListenerO);setTi
4、tleC服务器");setSize(600,400);setVisible(true);this.addWindowListener(newwinAdpt());try{serversocket二newDatagramSocket(5555);jta.append("服务器已启动正在监听端口5555..."+"");}catch(Exceptioneg){}while(true){try{byte[]databuf=newbyte[512];serverpacket=newDatagramP
5、acket(databuf,512);serversocket,receive(serverpacket);address二serverpacket,getAddress();port=serverpacket.getPort();datagram=newString(serverpacket.getData());jta.append(datagram+zz,z);}catch(I0Exceptionex){jta・append(ex・toString()+"");}}}publics
6、taticvoidmain(String[]args){newServer();}classwinAdptextendsWindowAdapter{publicvoidwindowClosing(WindowEvente){try{serversocket,close();serversocket=null;}catch(Exceptionea){}e.getWindow()•dispose();System,exit(0);}}classbuttonListenerimplementsActi
7、onListener{publicvoidactionPerformed(ActionEvente){try{datagram^jtf.getText();databuf二datagram.getBytes();serverpacket1二newDatagramPacket(databuf,databuf.length,address,port);serversocket,send(serverpacketl);}catch(IOExceptionex){jta.append(e.toStrin
8、g()+"");}}}}2、客户端Clientimportjava.io.*;importjava.net•*;importjava.awt.*;importjava,awt.event.*;importjavax.swing.*;publicclassClientextendsJFrame{JTextFieldjtf=newJTextField(30);JTextAreajta=newJTextAreaO;JButtonjb=newJButton(/z发送");JPaneljp二newJP