P
P
PlagueStarScream2017-08-08 11:01:08
Java
PlagueStarScream, 2017-08-08 11:01:08

Streaming bug?

there is a simple chat

Client code
import javax.swing.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    public class chatClient {
        JButton sendButton;
        JTextArea messageArea;
        BufferedReader reader;
        PrintWriter writer;
        JTextField messageField;
        JTextField nameField;

        public static void main(String[] args){
            chatClient client = new chatClient();
            client.go();
        }

        public void go(){
            JFrame frame = new JFrame();
            sendButton = new JButton("Send");
            sendButton.addActionListener(new SendButton());
            messageArea = new JTextArea(10,10);
            nameField = new JTextField(5);
            messageField = new JTextField(20);

            JPanel mainPanel = new JPanel();
            mainPanel.setLayout(new BoxLayout(mainPanel,BoxLayout.Y_AXIS));
            mainPanel.add(nameField);
            mainPanel.add(messageArea);
            mainPanel.add(messageField);
            mainPanel.add(sendButton);


            frame.getContentPane().add(BorderLayout.CENTER,mainPanel);
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

            frame.setSize(500,500);
            frame.setVisible(true);
            setNet();
        }

        public class secondStream implements Runnable{
            public void run(){
                //!!!!!! Поток на запись
                try {
                    Socket socket = new Socket("127.0.0.1", 5000);
                    writer = new PrintWriter(socket.getOutputStream());
                    writer.println(messageField.getText());
                    System.out.println("writer is work");
                    messageField.setText("");

                }
                catch (IOException ex){
                    ex.printStackTrace();
                }
            }
        }

        public class SendButton implements ActionListener{
            public void actionPerformed(ActionEvent ev){
                Runnable secStream = new secondStream();
                Thread t = new Thread(secStream);
                t.start();
            }
        }


        public void setNet(){
            try {

                while (true) {
                    //READER
                    Socket socket = new Socket("127.0.0.1",5000);
                    InputStreamReader isReader = new InputStreamReader(socket.getInputStream());
                    BufferedReader reader = new BufferedReader(isReader);
                    String servAnswer= reader.readLine();
                    messageArea.append( nameField.getText() + ": " + servAnswer + "\n");
                    reader.close();
                }
            }
            catch (IOException ex){
                ex.printStackTrace();
            }
        }

    }
and servers
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.net.*;


public class chatServer {
    String clientData;

   public static void main(String[] args){
        chatServer chServ = new chatServer();
        chServ.go();
   }
   public void go(){

        try {
            // READER
            ServerSocket serverSocket = new ServerSocket(5000);
            while (true) {
                System.out.println("connection normal*no");
                Socket socket = serverSocket.accept();
                InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
                BufferedReader reader = new BufferedReader(streamReader);
                    if((clientData = reader.readLine())!= null){
                        Runnable secStr = new secondStream();
                        Thread t = new Thread(secStr);
                        t.start();
                        System.out.println("Stream is work");

                    }
                reader.close();




           }
       }
        catch (IOException ex){
            ex.printStackTrace();
        }


   }
    public class secondStream implements Runnable{
        public void run() {
            //STREAM WRITER!
                try{
                    ServerSocket serverSocket = new ServerSocket(5000);
                        while (true) {
                            Socket socket = serverSocket.accept();
                            PrintWriter writer = new PrintWriter(socket.getOutputStream());
                            writer.println(clientData);
                            writer.close();
                        }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

            }
        }
    }


the field messageArearemains empty, the error is most likely in the streams, but there is no certainty, please point out the errors.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
ruslanys, 2017-08-17
@PlagueStarScream

To be honest, some kind of game is written. I did not even fully understand the problem statement from the code. But the problem in the code is obvious - incorrect work with sockets.
I rewrote the example, here's what I got:

Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {

    public static void main(String[] args) throws IOException {
        try (ServerSocket serverSocket = new ServerSocket(5000)) {
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("New connection: " + clientSocket.getRemoteSocketAddress().toString());

                ClientThread clientThread = new ClientThread(clientSocket);
                clientThread.start();
            }
        }
    }


    private static class ClientThread extends Thread {

        private final Socket socket;

        private ClientThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

                String request;
                while ((request = in.readLine()) != null) {
                    System.out.println("New message from " + socket.getRemoteSocketAddress().toString() + ": " + request);

                    StringBuilder sb = new StringBuilder(request);
                    String response = sb.reverse().toString();
                    out.println(response);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                System.out.println("Closing connection: " + socket.getRemoteSocketAddress().toString());

                try {
                    socket.close();
                } catch (IOException ignored) {}
            }
        }
    }

}
Customer
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ChatClient implements Runnable, ActionListener, OnMessageListener {

    private JTextArea messageArea;
    private JTextField messageField;

    private WorkerThread workerThread;

    public static void main(String[] args) {
        ChatClient client = new ChatClient();
        client.run();
    }

    private ChatClient() {
        initGui();
        initListeners();
    }

    private void initGui() {
        JFrame frame = new JFrame();
        JButton sendButton = new JButton("Send");
        sendButton.addActionListener(this);
        messageArea = new JTextArea(10, 10);
        messageField = new JTextField(20);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.add(messageArea);
        mainPanel.add(messageField);
        mainPanel.add(sendButton);


        frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.setSize(500, 500);
        frame.setVisible(true);
    }

    private void initListeners() {
        Observer.getInstance().addListener(this);
    }

    @Override
    public void run() {
        try {
            workerThread = new WorkerThread("127.0.0.1", 5000);
            workerThread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (workerThread == null) {
            return;
        }

        String request = messageField.getText();
        messageField.setText("");

        workerThread.sendMessage(request);
    }

    @Override
    public void onMessage(String message) {
        messageArea.append(message + System.lineSeparator());
    }


    private static class WorkerThread extends Thread {

        private final Socket socket;
        private final PrintWriter out;

        private WorkerThread(String host, int port) throws IOException {
            this.socket = new Socket(host, port);
            this.out = new PrintWriter(socket.getOutputStream(), true);

            System.out.println("Connection established...");
        }

        @Override
        public void run() {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                String message;
                while ((message = in.readLine()) != null) {
                    System.out.println("New message: " + message);
                    Observer.getInstance().fireEvent(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                System.out.println("Connection closing...");
                try {
                    out.close();
                    socket.close();
                } catch (Exception ignored) {}
            }
        }

        public synchronized void sendMessage(String message) {
            out.println(message);
        }
    }
}
public class Observer {

    private static final Observer INSTANCE = new Observer();

    public static Observer getInstance() {
        return INSTANCE;
    }


    private final Set<OnMessageListener> listeners;

    private Observer() {
        listeners = Collections.synchronizedSet(new HashSet<>());
    }

    public void addListener(OnMessageListener listener) {
        this.listeners.add(listener);
    }

    synchronized void fireEvent(String message) {
        for (OnMessageListener listener : listeners) {
            listener.onMessage(message);
        }
    }

}
public interface OnMessageListener {
    void onMessage(String message);
}

Something like this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question