資源描述:
《java聊天工具作業(yè)報告》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在工程資料-天天文庫。
1、Java實驗作業(yè)報告專業(yè):學號:姓名:一、實驗內(nèi)容利用java實現(xiàn)簡單的聊天平臺。二、實驗目的學習java網(wǎng)絡編程的基礎(chǔ)內(nèi)容,了解TCP/IP協(xié)議的簡單概念,和JAVA結(jié)合編程。三、實驗分析1、建立服務器CServero2、建立客戶端CCliento四、實現(xiàn)代碼1.服務器Serverimportjava.io.*;importjava.net.*;importjava,awt.*;importjava,awt.event.*;importjavax.swing.*;publicclassServ
2、erextendsJFrame{JTextFieldjtf=newJTextField(30);JTextAreajta=newJTextAreaO;JButtonjb=newJButton("發(fā)送");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("服務器已啟動正在監(jiān)聽端口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發(fā)送");JPaneljp二newJP