UDP socket chat application in java

I'm trying to create a very simple chat application in Java using UDP sockets. There is one server and multiple clients.

right now my code is :

Server :

package chat;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Set;

class User{
    InetAddress addr;
    int port;

    User(InetAddress a,int p){
        addr = a;
        port = p;
    }
}



public class Server {
    private static final int PORT = 27012;
    private static DatagramSocket sckt;
    private static DatagramPacket in,out;
    private static byte[] buffer;
    private static HashMap<String,User> users;
    public static void main(String[] args) {
        try{
            System.out.println("Opening port...");
            sckt = new DatagramSocket(PORT);
            users = new HashMap<String,User>();

        }
        catch(SocketException e){
            System.out.println("Port connection failed!");
            System.exit(1);
        }

        handleClient();
    }
        private static void sendMsg(InetAddress addr, int port, String msg){
            try{
            out = new DatagramPacket(msg.getBytes(),msg.length(),addr,port);
            sckt.send(out);
            }catch(IOException e){
                e.printStackTrace();
            }
        }
    private static void handleClient(){
        try{
            String msgIn,msgOut="",senderNick;
            do{
            buffer = new byte[256];
            in = new DatagramPacket(buffer,buffer.length);
            sckt.receive(in);
            InetAddress clientAddress = in.getAddress();
            int clientPort = in.getPort();
            msgIn = new String(in.getData(),0,in.getLength());
            //print msgIn
            //System.out.println(msgIn);
                        senderNick = msgIn.substring(0,msgIn.indexOf(" "));
                        msgIn = msgIn.substring(msgIn.indexOf(" ")+1);
            if(msgIn.equals("/connect")){
                //String nick = msgIn.substring(msgIn.indexOf(" ") + 1);
                System.out.println(senderNick);
                if(users.containsKey(senderNick)){
                    msgOut = "Nick already in use!";
                }
                else{
                    users.put(senderNick, new User(clientAddress,clientPort));
                    msgOut = "Connected!";
                }
                                sendMsg(clientAddress,clientPort,msgOut);
            }
                        else if(msgIn.equals("/list")){
                            Set userNames;
                            userNames = users.keySet();
                            msgOut = "Users : \n";
                            msgOut += userNames.toString();
                            sendMsg(clientAddress,clientPort,msgOut);
                        }
                        else if(msgIn.startsWith("/msg")){
                            String tmp = msgIn.substring(msgIn.indexOf(" ")+1);
                            String receiverName = tmp.substring(0,tmp.indexOf(" "));
                            String message = tmp.substring(tmp.indexOf(" ")+1);

                            if(!users.containsKey(receiverName)){
                                msgOut = "User " + receiverName + " not found!";
                                sendMsg(clientAddress,clientPort,msgOut);
                            }
                            else{
                                User receiver = users.get(receiverName);
                                msgOut = "Message from "+  senderNick  +" : "+message;
                                sendMsg(clientAddress,clientPort,"Message Sent!");
                                sendMsg(receiver.addr,receiver.port,msgOut);
                            }

                        }
                        else if(msgIn.startsWith("/nick")){
                            String newNick = msgIn.substring(msgIn.indexOf(" ")+1);
                            if(users.containsKey(newNick)){
                                msgOut = "Nick already in use!";
                            }
                            else{
                                users.put(newNick,users.get(senderNick));
                                users.remove(senderNick);
                                msgOut = "Nick changed!";
                            }
                            sendMsg(clientAddress,clientPort,msgOut);
                        }
                        else if(msgIn.equals("/disconnect")){
                            users.remove(senderNick);
                        }

            //out = new DatagramPacket(msgOut.getBytes(),msgOut.length(),clientAddress,clientPort);
            //sckt.send(out);
            }while(true);
        }
        catch(IOException e){
            e.printStackTrace();
        }
        finally{
            System.out.println("Closing connection.");
            sckt.close();
        }
    }

}

Client :

package chat;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Client {

    private static InetAddress host;
    private static final int PORT = 27012;
    private static DatagramSocket sckt;
    private static DatagramPacket in, out;
    private static byte[] buffer;
    private static String nick;

    static class MessageListener implements Runnable {
        //DatagramPacket in;
        //byte[] buffer;
        String reply;
        public void run() {
            do{
            try{
            buffer = new byte[256];
            in = new DatagramPacket(buffer,buffer.length);
            sckt.receive(in);
            reply = new String(in.getData(),0,in.getLength());
            System.out.println("SERVER> "+reply);
            }
            catch(IOException e){
                e.printStackTrace();
            }
            }while(true);
        }
    }

    public static void main(String[] args) {
        try {
            host = InetAddress.getLocalHost();

        } catch (UnknownHostException e) {
            System.out.println("Host not found!");
            System.exit(1);
        }
        connect();

    }

    private static void sendMsg(String msg) {
        try {
            out = new DatagramPacket(msg.getBytes(), msg.length(), host, PORT);
            sckt.send(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void connect() {
        Scanner sc = new Scanner(System.in);

        try {
            buffer = new byte[256];
            sckt = new DatagramSocket();
            String reply = "";
            do {
                System.out.println("Name: ");
                nick = sc.nextLine();
                sendMsg(nick + " /connect");
                in = new DatagramPacket(buffer, buffer.length);
                sckt.receive(in);
                reply = new String(in.getData(), 0, in.getLength());
                System.out.println("SERVER> " + reply);
            } while (!reply.equals("Connected!"));
            accessServer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void accessServer() {
        try {
            sckt = new DatagramSocket();
            Scanner sc = new Scanner(System.in);
            String msg = "", reply = "";
            Thread myT = new Thread(new MessageListener());
            myT.start();
            do {
                System.out.print("Enter Message: ");
                msg = sc.nextLine();
                if (!msg.equals("/quit")) {
                    buffer = new byte[256];

                    sendMsg(nick + " " + msg);


                } else {
                    sendMsg(nick + " /disconnect");
                }
            } while (!msg.equals("/quit"));

            sc.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Connection closing...");
            sckt.close();
        }

    }
}

I want to be able to send a message to a single user or to all the users but the problem is that i can't receive the message on the client because as it stands now the client only receives a message after it sends one to the server. So my thought was to use a thread that continuosly listens for messages from the server but it doesn't work. What's the easiest way to go about this ?

Answers


You are attempting to use the received datagram immediately, instead of waiting for the thread you created to receive a datagram and populate your in variable. You could either handle the received datagram directly in the thread's code, or signal the main thread when a datagram is received using a wait() / notify() scheme.


Need Your Help

How to create dot dat file in Delphi Prism?

namespaces binaryfiles text-files delphi-prism

I am new to Delphi Prism and been testing it out. When I hear and read programmers bad mouthing Delphi Prism for .NET, now I feel their pain. My God, I am having trouble with writing a simple code to

'undefined method init for Mysql:Class'

mysql ruby-on-rails osx ruby-on-rails-3

I've been having problems with a MySQL Server installation that got messed up after a power outage.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.