udp file transfer java with gui

Solutions on MaxInterview for udp file transfer java with gui by the best coders in the world

showing results for - "udp file transfer java with gui"
Juan Esteban
11 Jun 2020
1package udpclientserverapp;
2
3import java.awt.BorderLayout;
4import java.awt.Dimension;
5import java.awt.event.ActionEvent;
6import java.io.IOException;
7import java.net.DatagramPacket;
8import java.net.DatagramSocket;
9import java.net.InetAddress;
10import java.net.SocketException;
11import javax.swing.JFrame;
12import javax.swing.JScrollPane;
13import javax.swing.JTextArea;
14import javax.swing.JTextField;
15import javax.swing.SwingUtilities;
16
17
18public class Client extends JFrame{
19   private final JTextField msgField=new JTextField();
20   private final JTextArea msgArea=new JTextArea();
21   private DatagramSocket socket;
22
23   public Client(){
24      super("UDP Client");
25      super.add(msgField, BorderLayout.NORTH);
26      super.add(new JScrollPane(msgArea),
27         BorderLayout.CENTER);
28      super.setSize(new Dimension(450,350));
29      super.setVisible(true);
30      super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
31      msgArea.setEditable(false);
32
33      try{
34         socket=new DatagramSocket();
35      }catch(SocketException ex){
36         System.exit(1);
37      }
38
39      msgField.addActionListener((ActionEvent evt) -> {
40         try{
41            String msg=evt.getActionCommand();
42            showMsg("\nSendng message packet: "+msg);
43            byte buff[]=msg.getBytes();
44            DatagramPacket packetSend=
45               new DatagramPacket(buff, buff.length,
46               InetAddress.getLocalHost(), 12345);
47            socket.send(packetSend);
48            showMsg("\nPacket sent");
49         }catch(IOException ex){
50            showMsg(ex.getMessage());
51         }
52      });
53
54   }
55
56
57   public void readyToReceivPacket(){
58      while(true){
59         try{
60            byte buff[]=new byte[128];
61            DatagramPacket packet=
62               new DatagramPacket(buff,buff.length);
63            socket.receive(packet);
64            showMsg("\nHost: " + packet.getAddress()
65                    + "\nPort: " + packet.getPort()
66                    + "\nLength: " + packet.getLength()
67                    + "\nData: "
68                    + new String(packet.getData()));
69
70         }catch(IOException ex){
71            showMsg(ex.getMessage());
72         }
73      }
74   }
75
76   public void showMsg(final String msg) {
77      SwingUtilities.invokeLater(() -> {
78         msgArea.append(msg);
79      });
80   }
81
82}
83
84package udpclientserverapp;
85
86public class StartClient {
87   public static void main(String[] args) {
88      Client client=new Client();
89      client.readyToReceivPacket();
90   }
91}
92
similar questions
queries leading to this page
udp file transfer java with gui