Java Chatroom

Java Discuss, Java Chatroom at Programmers Lounge forum; One person must run the ChatServer application on a given port, and then the other people will type in the ...


Go Back   Gamerz Needs - For All Your Gaming Needs! > Technology Zone > Programmers Lounge > Java
Forgot Password? | Sign Up!

Notices

Advertisement
   

Reply
 
Bookmark this Thread Tools Display Modes
  #1  
Old 11-11-2007, 01:12 PM
Aimless's Avatar
is better than you
 
Last Online: Yesterday 12:59 PM
Join Date: Oct 2007
Age: 19
Posts: 159
Thanks: 4
Thanked 23 Times in 15 Posts
Nominated 0 Times in 0 Posts
TOTW/F/M Award(s): 0
Latest Blog:
Rep Power: 3
Aimless is on a distinguished road
Points: 349.38
Bank: 784.87
Total Points: 1,134.25
Java Chatroom

One person must run the ChatServer application on a given port, and then the other people will type in the host's ip address when it asks for host, and the port that is chosen by the host.

Note: I didn't spend much time on this, it's a substitute for mIRC in a sense; made this a long time ago.

ChatServer(Only one person needs to run it):
Code:
import javax.swing.*;
import javax.swing.event.*;
import java.net.*;
import java.util.*;
import java.io.*;

public class ChatServer
{
    public static ChatServer server;
    public static int port = 2444;
    public static ServerSocket serverSocket;
    public static Socket temp;
    public static ArrayList<User> users = new ArrayList<User>();
    public ChatServer(int ePort)
    {
        port = ePort;
        try{
            serverSocket = new ServerSocket(port);
            System.out.println("Server opened on port: " + port);
        }catch(Exception e){
            System.out.println("Server Port in use. Please choose another port.");
            System.exit(1);
        }
    }
    public static void main(String args[])
    {
        server = new ChatServer(Integer.parseInt(JOptionPane.showInputDialog("Enter the port #")));
        Thread mainLoop = new Thread(new Runnable()
        {
            public void run()
            {
                while(true)
                {
                    try{
                        temp = serverSocket.accept();
                    } catch(Exception e){}
                    User user = new User("nameless",temp);
                    users.add(user);
                    System.out.println("A new user has connected to the server.");
                    Thread t = new Thread(new Runnable()
                    {
                        public void run()
                        {
                            Socket temp2 = temp;
                            boolean stop = false;
                            while(!stop)
                            {
                                String msg = "poop";
                                try {
                                    msg = users.get(findUser(temp2)).getIn().readLine();
                                } catch(SocketException e) { 
                                    System.out.println(users.get(findUser(temp2)).getName() + " has disconnected from the server.");
                                    sendAll(users.get(findUser(temp2)).getName() + " has disconnected from the server.");
                                    users.remove(findUser(temp2));
                                    stop = true;
                                    break;
                                }
                                catch(IOException e){}
                                if(msg.startsWith("/"))
                                {
                                    if(msg.startsWith("/nick"))
                                    {
                                        String[] MSG = msg.split(" ");
                                        boolean found = false;
                                        for(int x = 0; x < users.size(); x++)
                                        {
                                            if(users.get(x).getName().equalsIgnoreCase(MSG[1]))
                                            {
                                                users.get(findUser(temp2)).getOut().println("Nickname is already in use.");
                                                found = true;
                                            }
                                        }
                                        if(!found)
                                        {
                                            sendAll(users.get(findUser(temp2)).getName() + " is now known as " + MSG[1]);
                                            users.get(findUser(temp2)).changeNick(MSG[1]);
                                        }
                                    }
                                }
                                else
                                {
                                    sendAll(msg,users.get(findUser(temp2)).getName());
                                }
                            }
                        }
                    });
                    t.start();
                }
            }
        });
        mainLoop.start();
    }

    public static int findUser(Socket temp)
    {
        for(int x = 0; x < users.size(); x++)
        {
            if(users.get(x).getSocket() == temp)
            {
                return x;
            }
        }
        return -1;
    }


    public static int findUserByName(String name)
    {
        for(int x = 0; x < users.size(); x++)
        {
            if(users.get(x).getName().equalsIgnoreCase(name))
            {
                return x;
            }
        }
        return -1;
    }

    public static void sendAll(String msg, String name)
    {
        for(int x = 0; x < users.size(); x++)
        {
            users.get(x).getOut().println(name + ":" + msg);
        }
    }

    public static void sendAll(String msg)
    {
        for(int x = 0; x < users.size(); x++)
        {
            users.get(x).getOut().println(msg);
        }
    }
}

class User
{
    public String username;
    public PrintWriter out;
    public BufferedReader in;
    public Socket userSocket;
    public User(String Eusername, Socket EuserSocket)
    {
        username = Eusername;
        userSocket = EuserSocket;
        try {
            out = new PrintWriter(userSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(userSocket.getInputStream()));
        } catch(Exception e){}
    }

    public PrintWriter getOut()
    {
        return out;
    }

    public BufferedReader getIn()
    {
        return in;
    }

    public String getName()
    {
        return username;
    }

    public Socket getSocket()
    {
        return userSocket;
    }

    public void changeNick(String newstring)
    {
        username = newstring;
    }
}
ChatClient(Needed to connect to the server):
Code:
import javax.swing.*;
import java.net.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;

public class ChatClient implements ActionListener
{
    public int port;
    public String host;
    public String msg;
    public PrintWriter out;
    public BufferedReader in;
    public JTextArea messages;
    public JPanel displayPanel, sendPanel;
    public JFrame main;
    public JScrollPane messagePane;
    public JTextField sendM;
    public JButton send;

    public static void main(String args[]) { ChatClient k = new ChatClient(); }
    public ChatClient()
    {
        try {
            host = JOptionPane.showInputDialog("Enter the host name of the server.");
            port = Integer.parseInt(JOptionPane.showInputDialog("Enter the port #"));
            Socket connection = new Socket(host, port);
            System.out.println("Now connected to " + host + ".");
            out = new PrintWriter(connection.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            Thread t = new Thread(new Runnable()
            {
                public void run()
                {
                    try{
                        displayMsg("You are now connected to host: " + host);
                        chooseNick();
                        String msg2 = in.readLine();
                        while(msg2 != null)
                        {
                            displayMsg(msg2);
                            msg2 = in.readLine();
                        }
                    } catch(Exception e) { e.printStackTrace(); }
                }
            });
            t.start();
        } catch(Exception e) { e.printStackTrace(); }

        main = new JFrame();
        main.setLayout(new BorderLayout());
        main.setSize(400,450);
        main.setResizable(false);

        displayPanel = new JPanel();
        messages = new JTextArea(20,35);
        messages.setEditable(false);
        messagePane = new JScrollPane(messages);
        displayPanel.add(messagePane);

        sendM = new JTextField(18);
        sendM.addKeyListener(new KeyListener()
        {
            public void keyPressed(KeyEvent e)
            {
                if(e.getKeyCode() == e.VK_ENTER) { send.doClick(); }
            }
            public void keyReleased(KeyEvent e){}
            public void keyTyped(KeyEvent e){}
        });

        send = new JButton("Send");
        send.addActionListener(this);

        sendPanel = new JPanel();
        sendPanel.add(sendM);
        sendPanel.add(send);

        main.getContentPane().add(displayPanel,BorderLayout.NORTH);
        main.getContentPane().add(sendPanel,BorderLayout.SOUTH);

        main.setVisible(true);
        sendM.requestFocusInWindow();
    }

    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == send)
        {
            out.println(sendM.getText());
            sendM.setText("");
        }
        sendM.requestFocusInWindow();
    }

    public void displayMsg(String themsg)
    {
        messages.append("\n" +themsg);
    }

    public void chooseNick()
    {
        String k = JOptionPane.showInputDialog("Choose a nickname.");
        out.println("/nick " + k);
    }
}
__________________
  #2  
Old 11-23-2007, 09:49 AM
dirky00018's Avatar
Violet Hole
 
Last Online: 11-19-2008 08:41 AM
Join Date: Mar 2007
Posts: 352
Thanks: 42
Thanked 18 Times in 12 Posts
Nominated 0 Times in 0 Posts
TOTW/F/M Award(s): 0
Latest Blog:
Rep Power: 5
dirky00018 is on a distinguished road
Points: 738.80
Bank: 3,730.62
Total Points: 4,469.42
Dark Blue - dirky00018 Dark Blue - dirky00018 Dark Blue - dirky00018 
noob question: what is the difference between implement and extends?
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

Advertisement
   


Main Navigation
Home
GzN Forums
GzN Games
GzN News
Top Games
GzN Cheats
GzN Articles
GzN Reviews
GzN Downloads
User Control Panel
Advertising
RSS Feed
2Moons
Adventure Quest
AirRivals
America's Army
Anarchy Online
Archlord
Audition
Battlefield Series
Cabal Online
Call Of Duty Series
Combat Arms
Conquer Online
Counter Strike
Day of Defeat
Deicide Online
Diablo Series
Doom Series
Drift City
Enemy Territory
Eudemons Online
Final Fantasy
Flyff (Fly For Fun)
General Game Discussion
Ghost Online
Granado Espada
Grand Theft Auto Series
Guild Wars
Gunbound
Gunz Online
Habbo Hotel
Half-Life 2
Hero Online
KartRider
Knights Online
Maple Story
Medal of Honor
MU Online
Neopets
Pangya
Quake Series
Ragnarok Online
Rappelz
Rakion
Red Orchestra
Rose Online
Runescape
Scions of Fate
Silkroad Online
Sims Series
Soldier Front
Starcraft
Tales of Pirates
Tibia
The Ship
Trickster Online
TS Online
Unreal Tournament
War Rock
WolfTeam
World of Warcraft & Series
Affiliates
COD4 Hacks
BF2 Hacks


All times are GMT -8. The time now is 03:15 PM.