Take the 2-minute tour ×

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?

share|improve this question

2 Answers 2

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.


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 = "";
    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.add(tf, BorderLayout.NORTH);
        f.add(new JScrollPane(ta), BorderLayout.CENTER);
        f.add(send, BorderLayout.SOUTH);
        f.setLocation(kind.offset, 300);
        DefaultCaret caret = (DefaultCaret) ta.getCaret();
        display(kind.activity + HOST + " on port " + PORT);
        thread = new Thread(this, kind.toString());

    public void start() {

    public void actionPerformed(ActionEvent ae) {
        String s = tf.getText();
        if (out != null) {

    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);
            while (true) {
        } catch (Exception e) {

    private void display(final String s) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                ta.append(s + "\u23CE\n");

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Echo(Kind.Server).start();
                new Echo(Kind.Client).start();
share|improve this answer
Ah, that reminds me: this related example shows how a server can accept multiple clients. –  trashgod Feb 16 '13 at 19:12
I keep seeing code all over the internet that happens to work because it uses Swing methods that happen to be thread-safe (such as setText), and I can't find a good example of how to have a background network thread send events to the EDT :/ –  Nicolás Mar 30 '13 at 1:47
@Nicolás: I usually use SwingWorker. –  trashgod Mar 30 '13 at 3:45

A basic example would be this: (based on tutorial from Socket Programming in Java, by A.P.Rajshekhar)

public static void main(String[] args) throws
    UnknownHostException, IOException, InterruptedException {

    Thread serverThread = new Thread(new Runnable() {

        public void run() {
            try {
                // create the server socket
                ServerSocket server = new ServerSocket(
                    8888, 5, InetAddress.getLocalHost());
                // wait until clients try to connect
                Socket client = server.accept();

                BufferedReader in = new BufferedReader(new

                // loop until the connection is closed
                String line;
                    // output what is received

            } catch (Exception e) {

    Thread clientThread = new Thread(new Runnable() {

        public void run() {
            try {
                // connect with the server
                Socket s = new Socket(InetAddress.getLocalHost(), 8888);

                // attach to socket's output stream with auto flush turned on

                // send some text
                // close the stream
            } catch (Exception e) {

    // start server
    // wait a bit
    // start client
share|improve this answer
Reformatted code; please revert if incorrect. –  trashgod Jul 14 '10 at 11:14
But is it possible to transfer data from both sides? Because a ServerSocket has no function that equals to what the client is having such as s.getOutputStream(),then how is it being done? What I mean is that i need to have conversation that would basic on what you wrote,but how the server would give back hus answer? –  Inbal Jul 14 '10 at 11:26
Once the connection is established - both sides are equal. Hence they can both send and receive data –  eugener Jul 14 '10 at 11:44

Your Answer


