0

This is my Server class that opens a server socket to get information from one client and then uses the class Users to send the String to all users in the array:

public class Server  {
    static ServerSocket server;
    static Socket client;
    static DataOutputStream out;
    static DataInputStream in;
    static int port = 7767;
    static Users[]User = new Users[10];

public static void main(String[] args)throws Exception{
    try {
        System.out.print("starting");
        server = new ServerSocket(port);
        while((client = server.accept() )!= null ){

             for(int i=0; i<10; i++){
                // System.out.println("input connection");
                 out= new DataOutputStream(client.getOutputStream());
                 in = new DataInputStream(client.getInputStream());
                if(User[i] == null)
                {
                    User[i] = new Users(out, in, User);
                    Thread thread = new Thread(User[i]);
                    thread.start();

                }
             }
        }

             } catch (IOException e) {

                e.printStackTrace();


}

This Users class just holds information of who is a client and then sends all users the string that the Server was sent, i used to get a NullPointException for message = in.readUTF(); but now, nothing happens at all.

public class Users implements Runnable {
DataOutputStream out;
DataInputStream in;
Users[] User = new Users[10];
public Users(DataOutputStream out, DataInputStream in, Users[] User)
{
    this.in = in;
    this.out = out;
    this.User = User;

}
public void run(){
    while(true){
        try{
            BufferedReader bri = new BufferedReader(new InputStreamReader(in));

        String  message;
        message = bri.readLine();

            for(int i=0; i<10; i++){
                if(User[i] != null)
            {
                    BufferedWriter br = new BufferedWriter(new OutputStreamWriter(out));
                User[i].br.write(message + "\n");
                }

            }

        }
        catch(IOException e){
    // catching and doing something about it and stuff
        }

}
}`

Client:(minus all the swing stuff to save question space)

public class Client implements WriteGui {
static Socket client;
static DataInputStream in;
static DataOutputStream out;
JTextArea msgout;
private JFrame frame;
private JTextField msgA;
private JTextField nameA;



/**
 * Create the application.
 */
public Client() {
    initialize();
    CStart();
}`

    public void actionPerformed(ActionEvent arg0) {
            if(nameA.getText() == ""){
             nameA.setText(getname());


            }
            String message;

            message = (nameA.getText()+": "+ msgA.getText());

        try {
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(out));
                br.write(message+"\n");


            } catch (IOException e) {
            msgout.append("error!");

            }


        }
public void write(String s) {
    msgout.append(s+ "/n" );

}
private String getname(){
    return JOptionPane.showInputDialog(frame,"fill out name" , "name", JOptionPane.QUESTION_MESSAGE);



}
public void CStart(){
 int port = 7767;
    String host = "localhost";
    try {

    client = new Socket(host, port);
    msgout.append("starting");
     in = new DataInputStream(client.getInputStream());
  out = new DataOutputStream(client.getOutputStream());
  Input input = new Input(in, this);
  Thread thread = new Thread(input);
  thread.start();

    }

    catch(Exception e) {
        msgout.append("error");
    }

I Also have a short input class that inputs the messages into the client:

public class Input implements Runnable  {
WriteGui gui;
DataInputStream in; 
static BufferedReader br;
public Input(DataInputStream in, WriteGui gui){
    this.in = in;
    this.gui = gui;

}

public void run() {
    String message;
br = new BufferedReader(new InputStreamReader(in));
try {
    message = br.readLine();
    gui.write(message);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

like I said, i got the error traced to the Users class, but the NullPointerException is not guaranteed to happen every time. It still seems to be in the Server/Users code though as it uses more resources at it should. Can anyone help me figure out why this Datainputstream does not seem to work?

Edit: it stopped producing NullPointerException, and now after pressing start after several attempts instead of the message, it sends a box shape. So it does seem to be a problem with the UTF reading. even with changing the OutputStreamWriter to just a DataInputStream, it will not work.

Alexandre
  • 148
  • 7
  • I think the problem is that you're writing the data using a `OutputStreamWriter` and you're trying to read it using a `DataInputStream`. Try to use the same type of stream to write/read the data. – Titus May 09 '16 at 04:13
  • I tried using just the DataInputStream and it didn't work, which was why i looked it up and some one had suggested the OutputStreamWriter for a similar problem – Alexandre May 09 '16 at 04:19
  • I have tried it without the static references, so that is not the cause of the resource management issues or my overall problem. I have left the static in the code here just to make the example neater as it doesn't seem to affect the problem. – Alexandre May 09 '16 at 04:26

2 Answers2

1

In order for the readUTF() method to work the data has to be formatted in a specific way which isn't the case when you write it using a OutputStreamWriter.

I suggest you use a BufferedReader and a BufferedWriter, use write(string+"\n") to write something and readLine() to read. In order for this to work, you have to add a new line \n at the end of each message.

Here is an example:

try(BufferedWriter bw = new BufferedWritter(new OutputStreamWriter(socker.getOutputStream()))){
    bw.write(message + "\n");
}catch(IOException e){
    e.printStackTrace();
}


try(BufferedReader br = new BufferedReader(new InputStreamReader(socker.getInputStream()))){
    String message = br.readLine();
}catch(IOException e){
    e.printStackTrace();
}
Titus
  • 20,544
  • 1
  • 19
  • 29
  • Would you suggest doing that with both sides of the stream? – Alexandre May 09 '16 at 04:47
  • @Alexandre Yes, you should use the same type of reader as the writer. And if you read the data line by line (using `readLine()`) make sure you terminate your messages with a new line character '\n'. – Titus May 09 '16 at 04:52
  • This is strange. I have just tested it a couple times using this suggestion, and it hasn't helped. The box and other strange symbols i had gotten have gone away, but the sent message hasn't come up. – Alexandre May 09 '16 at 05:03
  • @Alexandre Can you update your question to reflect the change that you have made ? – Titus May 09 '16 at 05:05
  • I updated this to match the changes I made to comply to your theory. This is getting to be a weird problem for me. – Alexandre May 10 '16 at 00:16
1

As you're now using a BufferedWriter, you need to flush() it at appropriate times, i.e. when you switch from writing to reading.

user207421
  • 289,834
  • 37
  • 266
  • 440
  • okay. could you be nice enough to provide an example or point me to one somewhere else? because i assume i need to synchronize it or time it as if i just flush the writer it can do that before the outputstream is gotten from the server? – Alexandre May 10 '16 at 01:29
  • You do not need an example of one line of code. Don't create imaginary problems. Just flush it before you read. This is not difficult. I cannot understand the part after 'because'. – user207421 May 10 '16 at 01:52
  • I get a NullPointerException again if i run the code with a flush after i send the message to the server, and a I also get the exception error if I flush the stream right after i send the message back to the client. – Alexandre May 10 '16 at 02:05
  • I really do expect any computer programmer to be able to code without `NullPointerExceptions`; not to bleat about them when engaged in solving a different problem; and when describing any problem requiring solution to do so in enough detail that a solution could actually be provided. Your question is now an under-documented duplicate. – user207421 May 10 '16 at 02:15