Simple network console chat on Java

In this post I will show you simple example of network chat on Java.

Let's start with our task.

Task

You need to implement console network chat. There must be a server instance and a client instance. Server starts, wait for single connection. Client starts, connects to server. Than client can write a message in its console. Message will be send to server and appears in server console. Server can do the same. Client and server can close the chat.

Let's start.

First, create basic class for handling typical operations by client and server in our task: get input from Std.in, set output to socket, get input from socket.

package chat;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    private Scanner in;
    private Scanner input;
    private PrintWriter out;
    private Thread threadIn;
    private Thread threadOut;
    public Client(Socket sock, String name) {
        try {
            in = new Scanner(sock.getInputStream());
            input = new Scanner(System.in);
            out = new PrintWriter(sock.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        threadOut = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (input.hasNext()) {
                        String q = input.next();
                        sendMsg(name+": "+q);
                        if (q.equalsIgnoreCase("close")) break;
                    }
                }
                close(sock);

            }
        });
        threadOut.start();
        threadIn = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (in.hasNext()) {
                        String w = in.nextLine();
                        System.out.println(w);
                        if (w.contains("close")) break;
                    }
                }
                close(sock);
            }
        });
        threadIn.start();
    }
    private void sendMsg(String w) {
        out.println(w);
        out.flush();
    }
    private void close(Socket sock){
        threadIn.interrupt();
        threadOut.interrupt();
        try {
            sock.close();
        } catch (Exception e) {}

    }
}

The only thing out cient and server will be different is getting of socket, creating of socket. Client will just connect to socket by static address. Server will be create socket and will be wait for connection from client.

Our server:

package chat;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {

    public ChatServer(){
        ServerSocket serv = null;
        Socket sock = null;
        try {
            serv = new ServerSocket(8189);
            System.out.println("Сервер запущен, ожидаем подключения...");
            sock = serv.accept();
            System.out.println("Клиент подключился");
            new Client(sock, "Сервер");
            while(true){
                if(sock.isClosed()){
                    break;
                }
            }
            serv.close();
            System.exit(0);
        } catch (IOException e) {
            System.out.println("Ошибка инициализации сервера");
        } finally {
            try {
                serv.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        new ChatServer();
    }
}

Our client:

package chat;

import java.io.IOException;
import java.net.Socket;

public class ChatClient {

    private final String SERVER_ADDR = "localhost";
    private final int SERVER_PORT = 8189;

    public ChatClient() {
        try {
            Socket sock = new Socket(SERVER_ADDR, SERVER_PORT);
            new Client(sock, "Клиент");
            while(true){
                if(sock.isClosed()){
                    break;
                }
            }
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ChatClient();
    }
}

For convenience all code available on Github https://github.com/A1esandr/alextech/tree/master/src/consolechat

Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed