Hello all

I have a chat room application where clients connect to server and can chat between each other, I am also trying to add a feature where a client can request a file from the server sucha s an image sound file or video

I am trying to convert the image into a byte array then send it over the socket through an ObjectOutputStream and receieve it on the client through an ObjectInputStream, however this is not working as the scanner on the client(used for recieving String 'chat' messages) seems to be picking it up .
I am not sure how to incorporate my ObjectInputStream into my client alongside the Scanner, is this even possible? Should I maybe be sending the 'chat' messages as objects thought the OOS and get rid of the printwriter?

Heres my code:

Relevent server code:

class ClientHandler extends Thread
        private Socket client;
        private Scanner input;
        private PrintWriter output; 
        private ObjectOutputStream objectOutput;//TODO:NEW CODE SEND MEDIA

        User user;

        public ClientHandler(Socket socket) throws IOException
            client = socket;    
            user = new User("", client);

            objectOutput = new ObjectOutputStream(client.getOutputStream());//TODO:NEW CODE SEND MEDIA
            input = new Scanner(client.getInputStream());
            output = new PrintWriter(client.getOutputStream());
            outputStreams.put(user, output);

        public void run()
            String received = "";//save full string received
            String messType=""; //store received string category after splitting
            String messName=""; //store name
            String messContent="";  //store actual message
            String messToSend="";

                if (input.hasNext())
                    received = input.nextLine();//"grab" incoming strings
                    System.out.println("Server Received: '" + received + "' From " + user.getUsername());//testing purposes

                    //Split string into type, name and message, separated by " " 
                    String ss[] = received.split(" ", 3);
                    messType=ss[0];//store type
                    messName =ss[1];//store sender name
                    messContent=ss[2];//store contents
                    messToSend = messName+":"+messContent;//message to send back
                    System.out.println("server line 131: message recieved and split, message to send to client: "+ messToSend); //TESTING PURPOSES

                    if (messType.equals("chatMsg"))//if statement to check incoming to see what it is, message, user etc
                        messToSend= "chatMSG"+messToSend;
                        }catch (IOException e) {
                            System.out.println("ERROR: chat message failes to send");
                    else if(messType.equals("setName"))
                        messContent = "addUser"+messContent;
                        }catch (IOException e) {
                            System.out.println("ERROR: 'usr joined' feailed to send");
                    else if(messType.equals("imgReq"))///////////////////////// IMAGE SENDING PART \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

                        System.out.println("Image requested");
                        try {
                            sendFile("beesting.jpg", objectOutput);
                        } catch (IOException e) {
                            System.out.println("Send File Error");
            }while (!messType.equals("QUIT"));//when user wants to quit

                System.out.println("Closing down connection...");
                sendToAll("usrQui" +user.getUsername() + " left chat");
            }catch(IOException ioEx){
                System.out.println("* Disconnection problem! *");
            outputStreams.remove(user, output);

    void sendUsers() throws IOException
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bao);

private static void sendMessage(String message, ObjectOutputStream objOutStream)

    Message mess = new Message(message);
    try {
    } catch (IOException e1) {
        // TODO Auto-generated catch block

///////////////////////// IMAGE SENDING PART \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
private static void sendFile(String fileName, ObjectOutputStream objOutStream) throws IOException
    //create fileInputStream to read file
    FileInputStream fileIn = new FileInputStream(fileName);

    //find out length
    long fileLen = (new File(fileName)).length();

    //convert length to int and create byteArray with this int
    int intFileLen = (int)fileLen;
    byte[] byteArray = new byte[intFileLen];
    //read file into byte array

    //Close FileInputStream...

    //send byteArray through stream to client 

Relevent Client code:

        public static void main(String[] args)  throws IOException
             audio = Applet.newAudioClip(new URL("file:cuckoo.au"));
             String userToAdd="";

            frame.setTitle("Electronic Chat Room");

            byte[] byteArray = null;
             do{//listen for response from server
                 if(networkInput.hasNext())//if server has responded
                    response = networkInput.nextLine();//take response
                    if (response.contains("addUser"))//check what type of response
                        userToAdd = response.substring(7);//cut response to relevant part
                        txtArUsers.append("\n" + userToAdd);//TODO: new users can't see users that connect before them, need to send whole list over
                        txtArDisplay.append("\n"+ userToAdd + " joined");
                    else if (response.contains("chatMSG"))
                        String sub = response.substring(7);
                        txtArDisplay.append("\n" + sub);
                    else if(response.contains("usrQui"))
                        String sub = response.substring(6);
                    else      //////////////////////////////////////////////RELEVANT PART RECEIVE IMAGE /////////////////////////////////////////////////////////////
                    //  txtArDisplay.append("\n" + response); //TESTING
                    //  txtArDisplay.append("----------------------------------");

                        try {
                            byteArray = (byte[])objectIn.readObject();
                        } catch (ClassNotFoundException e) {
                            // TODO Auto-generated catch block
                        FileOutputStream mediaStream;
                        mediaStream = new FileOutputStream("image.jpg");
                        image = new ImageIcon(byteArray);
                        System.out.println("Image received");

                }while (!message.equals("QUIT"));

Ive tried currting the code down to relevant bits full code below:

Thanks for any help
Server: http://pastebin.com/7u06KwVX
Client: http://pastebin.com/5V5NRfac
User: http://pastebin.com/K6MdcW5p
showImage: http://pastebin.com/B5AFA4xj

Recommended Answers

All 4 Replies

Mixing stream types on a single socket is guaranteed to cause chaos, so pick one type and stick to it. Object streams are the obvious way to go because they are most capable and simplest overall.
You can create a simple protocol to allow you to send different kinds of objects by preceeding the object with an identifier that says what's coming next. In broad outline the receiving end could like like:

enum MessageType (CHAT, IMAGE  etc

while (true) {
    MessageType nextMessageType = (MessageType) myObjectInputStream.readObject();
    switch (MessageType) {
        case CHAT:  readUTF() into a String, or maybe use a Message class and readObject() then cast to Message
        case IMAGE:  readObject() and cast to Image

Thank You! trying this out now, on the sending end do I need to change anything to send the Strings though the ObjectOutputStream or will they send though ok as they are?

You can just write/read them as objects (casting to String at the receiving end).
Alternatively you can use writeUTF/readUTF which give the same results but may be slightly more efficient

Im having trouble retrieving strings this way, No errors but nothing gets displayed on the client side??
Apologies fixed this now thank you for the help Im still working on transfering media but I am heading in the right direction now :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.