Java UDP chat and file transfer

Source: Internet
Author: User
Tags gettext

Package Rgy.com.udp3;import Java.awt.font;import Java.awt.gridlayout;import java.awt.event.actionevent;import Java.awt.event.actionlistener;import Java.awt.event.keyadapter;import Java.awt.event.keyevent;import Java.io.File ; Import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.net.datagrampacket;import Java.net.datagramsocket;import Java.net.inetaddress;import Java.net.socketaddress;import Java.sql.Date;import Java.text.simpledateformat;import Java.util.timer;import Java.util.timertask;import Javax.swing.JButton;import Javax.swing.jfilechooser;import Javax.swing.jframe;import Javax.swing.jlabel;import Javax.swing.JOptionPane; Import Javax.swing.jpanel;import Javax.swing.jscrollpane;import Javax.swing.jtextarea;import  Javax.swing.windowconstants;public class Client extends JFrame {//Join property private JPanel panel = new JPanel ();p rivate JButton Button_send = new JButton ("File send");p rivate JButton button_receive = new JButton ("Save As");p rivate jtextarea ta = new Jtextare A ();p RivaTe JScrollPane sp = new JScrollPane (TA);p rivate jtextarea ta_send = new JTextArea ();p rivate jscrollpane sp_send = new JSCR Ollpane (ta_send);p rivate JLabel label_filestate = new JLabel ("File status", Jlabel.center);p rivate JLabel label_feedback = new J Label ("Feedback", jlabel.center);//private inetaddress IP = null;private int otherport;private int Myport;datagramsocket socket;//receive file to prompt datagramsocket socket1;//receive file information Datagramsocket socket2;//receive the usual chat information//string filename = null;byte buffer[] = new Byte[1024];int FileLen = 0;int Numofblock = 0;int lastsize = 0;//string str_name;//public Client (String str _name, String str_ip, int otherport, int myport) {super (str_name); this.str_name = Str_name; This.setdefaultcloseoperation (Windowconstants.exit_on_close); This.setbounds (600, 250, 300, 400);// Added function code this.setlayout (new GridLayout (5, 1, 7, 7)); Ta.setlinewrap (true);//newline this.add (SP); Ta_send.setlinewrap (true); /newline This.add (sp_send), Button_send.setfont (New Font ("italic", 1)), Button_receive.setfont ("New Font" ("Italic", 1,));p Anel.add (button_send);p anel.add (button_receive); This.add (panel); This.add (label_filestate); This.add ( Label_feedback);//this.setvisible (true);//this.otherport = Otherport;this.myport = Myport;//button_ Send.addactionlistener (new ActionListener () {//Send file public void actionperformed (ActionEvent e) {// Select the file to be sent JFileChooser Filechooser = new JFileChooser (), int result = Filechooser.showopendialog (Client.this), if (result = = jfilechooser.approve_option) {try {File file = Filechooser.getselectedfile (); try {//sends the file name past string str_filename = Fil E.getname (); String Str_tip = "There are files, please handle:" + str_filename;byte[] filenamebuf = str_tip.getbytes ();D atagramsocket socket = new DATAGRAMSOC Ket ();D atagrampacket packet = new Datagrampacket (Filenamebuf, Filenamebuf.length,ip, Client.this.otherport); Socket.send (packet); Socket.close ()//fileinputstream fis = new FileInputStream (file)//Remove write memory from File//Send file length past int FileLen = Fis.available (); String Str_len = "" + filelen;byte[] filelenbuf = Str_len.getbytes ();Socket = new Datagramsocket ();p acket = new Datagrampacket (filelenbuf,filelenbuf.length, ip,client.this.otherport+1); Socket.send (packet); Socket.close ();//Send file body byte[] buf = new Byte[1024];int Numofblock = filelen/buf.length;//cycle times (This text  Pieces divided by how many blocks) int lastsize = fileLen% buf.length;//Last a little bit of a fraction of the number of bytes socket = new Datagramsocket (); for (int i = 0; i < Numofblock; i++) {fis.read (buf, 0, buf.length);//write memory packet = new Datagrampacket (buf,buf.length, ip,client.this.otherport+1); Socket.send (packet); Thread.Sleep (1); Simple to prevent packet loss}//send the last little bit of a fraction fis.read (buf, 0, lastsize);p acket = new Datagrampacket (buf,buf.length, IP, client.this.otherport+1); socket.send (packet); Thread.Sleep (1); Simple to prevent packet loss//fis.close (); Socket.close ();//label_filestate.settext ("File transfer complete. "); Ta.append (" ");//} catch (Exception ev) {System.out.println (EV);}} catch (Exception ex) {Joptionpane.showmessagedialog (client.this, "Error opening Document! ");}}}});/ //////////////button_receive.addactionlistener (new ActionListener () {//Receive file public void ActionperformEd (ActionEvent e) {//Select the file to receive JFileChooser Filechooser = new JFileChooser (); int result = Filechooser.showsavedialog ( Client.this), if (result = = Jfilechooser.approve_option) {try {file File2 = Filechooser.getselectedfile (); try {file file1 = new File ("d:\\tt\\" + filename); SaveAs (File1, file2);//label_filestate.settext ("File receive complete!

"); Ta.append (" The file has been processed!! \ n ");} catch (Exception ex) {System.out.println (ex);}} catch (Exception ex) {Joptionpane.showmessagedialog (Client.this, "Open Save Error! ");}}}});/ /ta_send.addkeylistener (New Keyadapter () {public void keypressed (KeyEvent ke) {String str_chat = Client.this.str_name + " Say: "+ ta_send.gettext (); byte buf[] = Str_chat.getbytes (); if (Ke.iscontroldown () && ke.getkeycode () = = KEYEVENT.V K_enter) {try {datagramsocket socket = new Datagramsocket ();D atagrampacket packet = new Datagrampacket (buf,buf.length, IP , client.this.otherport+2); socket.send (packet); Ta.append ("I said:" +ta_send.gettext () + "\ n"); Ta_send.settext ("");} catch (Exception ex) {System.out.println (ex);}}}); /try {ip = inetaddress.getbyname (STR_IP); socket = new Datagramsocket (this.myport); socket1 = new Datagramsocket ( This.myport + 1); Socket2 = new Datagramsocket (This.myport + 2); Timer timer = new timer ();//timer, flush Receive Message timer.schedule (new mytimertask_receive (), 0, +); while (Socket!=null) {try {// byte filetipbuf[] = new BYTe[256];//prevents the file name word from being too long (up to 256 characters) Datagrampacket Packet_tip = new Datagrampacket (filetipbuf,0, filetipbuf.length); Socket.receive (Packet_tip); String str_filetip = new String (Packet_tip.getdata (), 0,packet_tip.getlength ()), filename = str_filetip.substring (8); Ta.append (Str_filetip + "\ n");//Receive file Length (bytes) byte[] Filelenbuf = new byte[12];//capable of transmitting 1T files Datagrampacket Packet_len = new D Atagrampacket (filelenbuf,filelenbuf.length); socket1.receive (Packet_len); String str_filelen = new String (Filelenbuf, 0,packet_len.getlength ()); FileLen = Integer.parseint (Str_filelen); Ta.append ("File size:" + fileLen + "bytes," + (filelen/1024) + "KB," + (filelen/1024/1024) + "mb\n");//datagrampacket pack Et_file = new Datagrampacket (buffer, 0,buffer.length), Numofblock = filelen/buffer.length;//cycles (how many blocks are divided into the file) Lastsize = FileLen% buffer.length;//The last tiny fraction of the number of bytes file File = new file ("d:\\tt\\" + filename); FileOutputStream fos = new FileOutputStream (file);//Remove from memory deposit file for (int i = 0; i < Numofblock; i++) {packet_file =New Datagrampacket (buffer, 0,buffer.length); socket1.receive (packet_file);//Receive Data fos.write via socket (buffer, 0, 1024);// Write file}//receive last little bit of packet_file = new Datagrampacket (buffer, 0, lastsize); socket1.receive (packet_file);// Receive data via socket fos.write (buffer, 0, lastsize);//write File Fos.close ();//Feedback packet} catch (Exception e) {System.out.println (e);}}} catch (Exception e) {System.out.println (e);}} public void SaveAs (file file1, file file2) {//Save File1 as File2, and delete file1try {FileInputStream fis = new FileInputStream (file1 ); FileOutputStream fos = new FileOutputStream (file2); byte buf[] = new Byte[1024];int len = 0;while (len = Fis.read (BUF))! = -1) {fos.write (buf, 0, Len);} Fis.close (); Fos.close (); File1.delete ();} catch (Exception ex) {System.out.println (ex);}} Class Mytimertask_receive extends TimerTask {public void run () {try{byte chatbuf[] = new byte[512];D atagrampacket packet_c hat = new Datagrampacket (chatbuf, 0,chatbuf.length); socket2.receive (Packet_chat); String str_chat = new String (Packet_chat.getdata (), 0,PACket_chat.getlength ()); Ta.append (str_chat + "\ n");} catch (Exception ex) {System.out.println (ex);}}} public static void Main (String args[]) {new Client ("Mary", " 127.0.0.2 ", 6000, 10000);}}


Java UDP chat and file transfer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.