为什么服务器不写入客户端?

时间:2016-05-09 04:04:05

标签: java sockets tcp datainputstream

这是我的Server类,它打开服务器套接字以从一个客户端获取信息,然后使用类Users将String发送给数组中的所有用户:

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();


}

此Users类只保存who是客户端的信息,然后向所有用户发送服务器发送的字符串,我曾经为message = in.readUTF();获取NullPointException,但现在根本没有任何事情发生。

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
        }

}
}`

客户:(减去所有用于节省问题空间的摆动东西)

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");
    }

我还有一个简短的输入类,可以将消息输入客户端:

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();
}
像我说的那样,我得到了跟踪到Users类的错误,但是每次都不能保证NullPointerException会发生。它似乎仍然在Server / Users代码中,因为它应该使用更多的资源。 任何人都可以帮我弄清楚为什么这个Datainputstream似乎不起作用?

编辑:它停止产生NullPointerException,现在在几次尝试而不是消息后按下启动后,它会发送一个盒子形状。因此,UTF读数似乎确实存在问题。即使将OutputStreamWriter更改为DataInputStream,它也无法工作。

2 个答案:

答案 0 :(得分:1)

为了使readUTF()方法起作用,数据必须以特定的方式进行格式化,而使用OutputStreamWriter进行编写则不是这种情况。

我建议您使用BufferedReaderBufferedWriter,使用write(string+"\n")撰写内容并readLine()阅读。为了实现这一点,您必须在每封邮件的末尾添加一个新行\n

以下是一个例子:

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();
}

答案 1 :(得分:1)

正如您现在使用的是BufferedWriter,您需要在适当的时间flush(),即当您从写作切换到阅读时。