Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket using in a swing applet

Tags:

I should made a server & client in Java,based on Swing and gui.I neeed to make somehow a socket that will go from the server to the client and from the client to the server, and will pass some kind of a string.I would like to have later a function that would do several things according to the string that would be in the socket.
For some reason I couldn't find a simple example for code that shows how it's done in a simple way.
Anyone has any simple example or can explain how is it being done?

like image 301
Inbal Avatar asked Jul 14 '10 08:07

Inbal


People also ask

Do Java sockets use TCP or UDP?

Yes, Socket and ServerSocket use TCP/IP. The package overview for the java.net package is explicit about this, but it's easy to overlook. UDP is handled by the DatagramSocket class.

What is socket in OOP?

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.

What is socket in Java with example?

Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server. When the connection is made, the server creates a socket object on its end of the communication.

What is TCP IP socket in Java?

TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, stream-based connections between hosts on the Internet. A socket can be used to connect Java's I/O system to other programs that may reside either on the local machine or on any other machine on the Internet.


1 Answers

Based on this example, here's a simple network client-server pair using Swing. Note some issues related to correct synchronization: The GUI itself is constructed on the event dispatch thread using invokeLater(). In addition, the code relies on the thread safety of append(). Finally, it incorporates a handy tip from the article Text Area Scrolling.

Update: In Java 7, append() is no longer marked as thread safe; invokeLater() is used in display() to sequence updates.

image

package net;  import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.Scanner; import javax.swing.*; import javax.swing.text.DefaultCaret;  /**  * A simple network client-server pair  * @http://stackoverflow.com/questions/3245805  */ public class Echo implements ActionListener, Runnable {      private static final String HOST = "127.0.0.1";     private static final int PORT = 12345;     private final JFrame f = new JFrame();     private final JTextField tf = new JTextField(25);     private final JTextArea ta = new JTextArea(15, 25);     private final JButton send = new JButton("Send");     private volatile PrintWriter out;     private Scanner in;     private Thread thread;     private Kind kind;      public static enum Kind {          Client(100, "Trying"), Server(500, "Awaiting");         private int offset;         private String activity;          private Kind(int offset, String activity) {             this.offset = offset;             this.activity = activity;         }     }      public Echo(Kind kind) {         this.kind = kind;         f.setTitle("Echo " + kind);         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         f.getRootPane().setDefaultButton(send);         f.add(tf, BorderLayout.NORTH);         f.add(new JScrollPane(ta), BorderLayout.CENTER);         f.add(send, BorderLayout.SOUTH);         f.setLocation(kind.offset, 300);         f.pack();         send.addActionListener(this);         ta.setLineWrap(true);         ta.setWrapStyleWord(true);         DefaultCaret caret = (DefaultCaret) ta.getCaret();         caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);         display(kind.activity + HOST + " on port " + PORT);         thread = new Thread(this, kind.toString());     }      public void start() {         f.setVisible(true);         thread.start();     }      //@Override     public void actionPerformed(ActionEvent ae) {         String s = tf.getText();         if (out != null) {             out.println(s);         }         display(s);         tf.setText("");     }      //@Override     public void run() {         try {             Socket socket;             if (kind == Kind.Client) {                 socket = new Socket(HOST, PORT);             } else {                 ServerSocket ss = new ServerSocket(PORT);                 socket = ss.accept();             }             in = new Scanner(socket.getInputStream());             out = new PrintWriter(socket.getOutputStream(), true);             display("Connected");             while (true) {                 display(in.nextLine());             }         } catch (Exception e) {             display(e.getMessage());             e.printStackTrace(System.err);         }     }      private void display(final String s) {         EventQueue.invokeLater(new Runnable() {             //@Override             public void run() {                 ta.append(s + "\u23CE\n");             }         });     }      public static void main(String[] args) {         EventQueue.invokeLater(new Runnable() {             //@Override             public void run() {                 new Echo(Kind.Server).start();                 new Echo(Kind.Client).start();             }         });     } } 
like image 161
trashgod Avatar answered Oct 14 '22 21:10

trashgod