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);
userList.add(user);
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="";
do{
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;
try{
sendToAll(messToSend);
}catch (IOException e) {
System.out.println("ERROR: chat message failes to send");
}
}
else if(messType.equals("setName"))
{
user.setName(messContent);
System.out.println(user.getUsername());
messContent = "addUser"+messContent;
try{
sendToAll(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
try{
System.out.println("Closing down connection...");
sendToAll("usrQui" +user.getUsername() + " left chat");
input.close();
output.close();
client.close();
System.out.println(user.getUsername());
}catch(IOException ioEx){
System.out.println("* Disconnection problem! *");
}
outputStreams.remove(user, output);
userList.remove(user);
}
}
void sendUsers() throws IOException
{
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bao);
oos.writeObject(userList);
oos.close();
}
private static void sendMessage(String message, ObjectOutputStream objOutStream)
{
Message mess = new Message(message);
try {
objOutStream.writeObject(mess);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
///////////////////////// 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];
System.out.println(intFileLen);
//read file into byte array
fileIn.read(byteArray);
//Close FileInputStream...
fileIn.close();
//send byteArray through stream to client
System.out.println(byteArray[0]);
objOutStream.writeObject(byteArray);
objOutStream.flush();
}
Relevent Client code:
public static void main(String[] args) throws IOException
{
audio = Applet.newAudioClip(new URL("file:cuckoo.au"));
String userToAdd="";
frame.setSize(500,70);
frame.setVisible(true);
frame.setTitle("Electronic Chat Room");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
connect();
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
{
System.out.println(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);
txtArDisplay.append("\n"+sub);
}
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
e.printStackTrace();
}
FileOutputStream mediaStream;
mediaStream = new FileOutputStream("image.jpg");
mediaStream.write(byteArray);
image = new ImageIcon(byteArray);
showImage();
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