@PlagueStarScream

Ошибка с потоками?

есть простейший чат
код клиента
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();
            }
        }

    }
и сервера
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();
                }

            }
        }
    }



поле messageArea остается пустым, ошибка скорее всего в потоках но уверенности нет, просьба указать на ошибки.
  • Вопрос задан
  • 476 просмотров
Решения вопроса 1
@ruslanys
Честно говоря, написана дичь какая-то. Я по коду даже не до конца разобрался в постановке задаче. Но проблема в коде очевидна - неправильная работа с сокетами.

Я переписал пример, вот что у меня получилось:
Сервер
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) {}
            }
        }
    }

}
Клиент
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);
}


Как-то так.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы