Java – data is not written to the printwriter

I'm actually trying to create a program:

public void setUpNetwork(){
    try {
            Socket sock = new Socket("localhost",1101);
            InputStreamReader read = new InputStreamReader(sock.getInputStream());
            buff = new BufferedReader(read);
            write = new PrintWriter(sock.getOutputStream());
            System.out.println("Network Established");
        } catch (UnkNownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
}

Here, once the socket connection is established, I try to pass the data entered by the user to the print stream, and then print the data in the console

There are only so many server classes for me:

ServerSocket server = new ServerSocket(1101);
        Socket socket = server.accept();

When I run it (when running, I run the server first, and then run the chatsetup class), there is nothing on the console! Because of sersock Accept () gives a socket connection with different ports, and the client cannot communicate with the server? If so, I need to pass the socket object from the server to setupnetwork () in another class so that I can create an input stream on it What shall I do?

Edit:

I have modified the whole program! I'm using swing to create a GUI. When the user enters text in the text field and clicks send, it will trigger the listener. This is where I add text to printwriter The whole code is as follows: And setupnetwork () are also part of this class (not included below)

Edit: server code contained in the same program and start a new thread for the server

public class ChatGraphs {

JTextField field;
JTextArea area;
PrintWriter write;
BufferedReader buff;
Socket sock;

public static void main(String[] args) {
    ChatGraphs grap = new ChatGraphs();
    grap.doIt();
}

private void doIt() {
    JFrame frame = new JFrame();
    frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);


    JPanel allPanel = new JPanel();
    allPanel.setLayout(new @R_475_2419@Layout(allPanel,@R_475_2419@Layout.Y_AXIS));

    JPanel areaPanel = new JPanel();
    areaPanel.setLayout(new FlowLayout());
    JLabel alabel = new JLabel("Chats");
    area = new JTextArea(20,50);
    area.setEditable(false);
    areaPanel.add(alabel);
    areaPanel.add(area);

    JPanel textPanel = new JPanel();
    textPanel.setLayout(new FlowLayout());
    JLabel flabel = new JLabel("Enter");
    field = new JTextField(20);
    JButton button = new JButton("Send");
    button.addActionListener(new ButtonListen());
    textPanel.add(flabel);
    textPanel.add(field);
    textPanel.add(button);

    allPanel.add(areaPanel);
    allPanel.add(textPanel);

    ConnectServer con = new ConnectServer();
    Thread t = new Thread(con);
    t.start();

    AddData add = new AddData();
    Thread t1 = new Thread(add);
    t1.start();

    //setUpServer();
    setUpClient();

    frame.setSize(700,500);
    frame.setVisible(true);
    frame.getContentPane().add(allPanel);
}

public class ButtonListen implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent arg0) {     
        write.println(field.getText());
        write.flush();
        field.setText("");
        field.setRequestFocusEnabled(true);

    }
}

private void setUpClient(){
    try {
        sock = new Socket("localhost",1101);
        InputStreamReader read = new InputStreamReader(sock.getInputStream());
        buff = new BufferedReader(read);
        System.out.println("Network Established");
    } catch (UnkNownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public class AddData implements Runnable{

    @Override
    public void run() {
        String line="";
        try {
            while((line=buff.readLine())!=null){
                System.out.println("Another net");
                area.append(line);
            }
            buff.close();
            write.close();
            sock.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public class ConnectServer implements Runnable{

    public void run() {
        ServerSocket sersock = null;
        Socket sock = null;
        try {
                sersock = new ServerSocket(1101);
                sock = sersock.accept();
                write = new PrintWriter(sock.getOutputStream());
                sersock.close();
                sock.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }

}

The exceptions I get are:

Exception in thread "Thread-2" java.lang.NullPointerException
    at org.sockets.ChatGraphs$AddData.run(ChatGraphs.java:120) // This line is : while((line=buff.readLine())!=null)
    at java.lang.Thread.run(UnkNown Source)
Network Established

Solution

How do clients and servers find each other through sockets?

>The client needs to know the network address (IP address) of the server and the port number on which the server is listening. > The server only needs to know which port it is listening on If it has more network interfaces with different IP addresses, you can choose to restrict the server to listen to one of the network interfaces (one IP address)

Therefore, the code snippet for connecting the client to the server is as follows:

Socket socket4Client = new Socket("IP-Address,e.g. 123.45.67.89",PORT_NUMBER);

And the code snippet of the server is as follows:

ServerSocket serverSocket = new ServerSocket(PORT_NUMBER);
Socket socket4Server = serverSocket.accept(); // Waits for a Client to connect

On the server side, you probably want to start a new thread for each incoming connection Look at some very simple (but not overly simplified) examples of these tiny applications

Edit / add:

About NullPointerException (

You get an exception because buff is null This is because the thread connectserver starts before calling the method setupclient() You can create Thread, but you must call setUpClient () before actually starting () threads.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>