Chatty

User -> Server - login/logoff commands - status commands

Server -> User - users online/offline

User -> User - direct messages - broadcast messages / group messaging / using # channels or topics

Commands - login

Multi Chat User

CODE

Server Main

public class ServerMain {
public static void main(String[] args) {
    //run locally using "telnet localhost [port]" in terminal or Powershell
    int port = 8818;
    Server server = new Server(port);
    //Run thread from Server object
    server.start();
    }

}

Server Worker

public class ServerWorker extends Thread{

private final Socket clientSocket;
private final Server server;
private String ulogin = null; //username for this serverworker
private OutputStream os;
public ServerWorker(Server server, Socket clientSocket){
    this.server = server;
    this.clientSocket = clientSocket;
}

@Override
public void run(){
    try {
        handleClientSocket();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public String getLogin(){
    return ulogin;
}

//method that works on thread
private void handleClientSocket() throws IOException, InterruptedException {
    //Bidirectional client server communication
    InputStream is = clientSocket.getInputStream();
    clientSocket.getOutputStream();
    this.os = clientSocket.getOutputStream();

    //BufferedReader to read line by line
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    String line;
    while ( (line = reader.readLine()) != null){
        //split line into array of tokens
        String[] tokens = line.split(" ");
        if (tokens != null && tokens.length > 0){
            String cmd = tokens[0]; //first word in line
            //RECOGNIZE COMMANDS
            //terminate connection on quit command
            if ("quit".equalsIgnoreCase(cmd) || "logoff".equals(cmd)){
                handleLogoff();
                break;
            } else if("login".equalsIgnoreCase(cmd)){
                handleLogin(os, tokens);
            } else if("msg".equalsIgnoreCase(cmd)){
                String[] tokensMsg = new String[tokens.length - 2];
                for (int i = 2; i < tokens.length; i++){
                    tokensMsg[i - 2] = tokens[i];
                }
                String toSend = String.join(" ",tokensMsg);
                handleMessage(tokens[1], toSend);
            } else if("join".equalsIgnoreCase(cmd)){
                handleJoin(tokens);
            } else if("leave".equalsIgnoreCase(cmd)){
                handleLeave(tokens);
            }
            else {
                String msg = "unknown command: " + cmd + "\n";
                os.write(msg.getBytes());
            }

            /* ECHO BOT
            String msg = "You typed: " + line + "\n";
            os.write(msg.getBytes());
            */
        }
    }

    //Output from server to client
    /*
    OutputStream os = clientSocket.getOutputStream();
    for(int i = 0; i<10; i++){
        os.write(("\nThe time now is " + new Date()).getBytes());
        Thread.sleep(1000);
    }
    */

    //close socket
    clientSocket.close();
}

private void handleLeave(String[] tokens) {
    if (tokens.length > 1){
        String topic = tokens[1];
        topicSet.remove(topic);
    }
}

public boolean isMemberOfTopic(String topic){
    return topicSet.contains(topic);
}

private void handleJoin(String[] tokens) {
    if (tokens.length > 1){
        String topic = tokens[1];
        topicSet.add(topic);
    }
}

//format: "msg" "login(user)" text...
//format: "msg" "#topic" body...
private void handleMessage(String sendTo, String text) throws IOException {
    //check if group/topic message
    boolean isTopic = sendTo.charAt(0) == '#';

    //Iterate through list of server workers to find worker login
    List

Play over server

Play over server

Game Client

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

public class GameClient
{
    public int iCounter;
    public String[][] iBoard;

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

    public GameClient()
    {
        Socket client;
        DataInputStream input;
        DataOutputStream output;

        Scanner iScan = new Scanner(System.in);
        System.out.println("--------------CLIENT--------------");
        System.out.print("ENTER IP ADDRESS: ");
        String iIPAdd = iScan.next();
        System.out.print("ENTER PORT NUMBER: ");
        int iPort = iScan.nextInt();
        System.out.println("----------------------------------");
        iCounter = 0;

        int iCount = 1;
        iBoard = new String[3][3];
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                iBoard[i][j] = Integer.toString(iCount);
                iCount++;
            }
        }

        try
        {
            System.out.println("CLIENT: Client started");

            // Step 1: Create a Socket to make connection.
            client = new Socket(iIPAdd, iPort);
            System.out.println("Connected to: " + client.getInetAddress().getHostName());

            // Step 2: Get the input and output streams.
            input = new DataInputStream(client.getInputStream());
            output = new DataOutputStream(client.getOutputStream());
            System.out.println("CLIENT: Got I/O Streams");

            // Step 3: Process connection.
            while (iCounter <= 9)
            {
                int iOPlayed = Integer.parseInt(input.readUTF());
                addToBoard(iOPlayed, "O");
                iCounter++;
                displayBoard();

                System.out.print(iCounter + ") 'X' TO PLAY: ");
                int iXTurn = iScan.nextInt();
                addToBoard(iXTurn, "X");

                //displayBoard();
                iCounter++;

                //X TURN
                output.writeUTF(Integer.toString(iXTurn));
            }
            //output.writeUTF("Thank you.");

            // Step 4: Close connection.
            System.out.println("CLIENT: Transmission complete. " + "Closing connection.");
            client.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void displayBoard()
    {
        System.out.println("-----");
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                if (j == 2)
                {
                    System.out.println(iBoard[i][j]);
                }
                else
                {
                    System.out.print(iBoard[i][j] + "|");
                }
            }
            if (i < 2)
                System.out.println("-+-+-");
        }
        System.out.println("-----");
    }

    public void addToBoard(int iNum, String iPlayer)
    {
        switch (iNum)
        {
            case 1: iBoard[0][0] = iPlayer;
                break;
            case 2: iBoard[0][1] = iPlayer;
                break;
            case 3: iBoard[0][2] = iPlayer;
                break;
            case 4: iBoard[1][0] = iPlayer;
                break;
            case 5: iBoard[1][1] = iPlayer;
                break;
            case 6: iBoard[1][2] = iPlayer;
                break;
            case 7: iBoard[2][0] = iPlayer;
                break;
            case 8: iBoard[2][1] = iPlayer;
                break;
            default: iBoard[2][2] = iPlayer;
                break;
        }
    }
}

Game server

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class GameServer
{
    public String[][] iBoard;
    public int iCounter;

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

    public GameServer()
    {
        ServerSocket server;
        Socket connection;
        DataOutputStream output;
        DataInputStream input;

        Scanner iScan = new Scanner(System.in);
        System.out.println("--------------SERVER--------------");
        System.out.print("ENTER PORT NUMBER: ");
        int iPort = iScan.nextInt();
        System.out.println("----------------------------------");

        //GAME SETUP:
        int iCount = 1;
        iBoard = new String[3][3];
        System.out.println("OXO BOARD:");
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                iBoard[i][j] = Integer.toString(iCount);
                iCount++;
            }
        }
        displayBoard();
        iCounter = 0;

        try
        {
            // Step 1: Create a ServerSocket.
            server = new ServerSocket(iPort, 1);
            System.out.println("SERVER: Server started " + InetAddress.getLocalHost().getHostAddress());

            while (true)
            {
                // Step 2: Wait for a connection.
                connection = server.accept();
                System.out.println("SERVER: Connection received from: " + connection.getInetAddress().getHostName());

                // Step 3: Get input and output streams.
                input = new DataInputStream(connection.getInputStream());
                output = new DataOutputStream(connection.getOutputStream());
                System.out.println("SERVER: Got I/O streams");

                // Step 4: Process connection.
                //TURN 1
                System.out.print(iCounter + ") 'O' TO PLAY: ");
                int iOTurn = iScan.nextInt();
                addToBoard(iOTurn, "O");

                //displayBoard();
                iCounter++;

                //X TURN
                output.writeUTF(Integer.toString(iOTurn));

                while (iCounter < 9)
                {
                    int iXPlayed = Integer.parseInt(input.readUTF());
                    addToBoard(iXPlayed, "X");
                    iCounter++;
                    displayBoard();

                    System.out.print(iCounter + ") 'O' TO PLAY: ");
                    iOTurn = iScan.nextInt();
                    addToBoard(iOTurn, "O");

                    //displayBoard();
                    iCounter++;

                    //X TURN
                    output.writeUTF(Integer.toString(iOTurn));
                }

                // Step 5: Close connection.
                System.out.println("SERVER: Transmission complete. " + "Closing socket.");
                connection.close();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void displayBoard()
    {
        System.out.println("-----");
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                if (j == 2)
                {
                    System.out.println(iBoard[i][j]);
                }
                else
                {
                    System.out.print(iBoard[i][j] + "|");
                }
            }
            if (i < 2)
                System.out.println("-+-+-");
        }
        System.out.println("-----");
    }

    public void addToBoard(int iNum, String iPlayer)
    {
        switch (iNum)
        {
            case 1: iBoard[0][0] = iPlayer;
                break;
            case 2: iBoard[0][1] = iPlayer;
                break;
            case 3: iBoard[0][2] = iPlayer;
                break;
            case 4: iBoard[1][0] = iPlayer;
                break;
            case 5: iBoard[1][1] = iPlayer;
                break;
            case 6: iBoard[1][2] = iPlayer;
                break;
            case 7: iBoard[2][0] = iPlayer;
                break;
            case 8: iBoard[2][1] = iPlayer;
                break;
            default: iBoard[2][2] = iPlayer;
                break;
        }
    }
}

GitHub – LadySith

Yaa

Lusaka, Zambia

Computer Science student and a bunch of other things.