繁体   English   中英

Java服务器客户端网络

[英]Java server client networking

我是否应该在每次客户端GUI发送消息时打开或关闭连接,或者一次打开连接并保持打开状态?

我使用BufferedWriter发送数据,但此方法似乎只工作一次,执行了写入和刷新方法后,我只能向我的服务器发送1条消息,然后它没有收到正在发送的数据...

客户端连接-将数据发送到服务器(第一次)-Works客户端再次发送数据-服务器控制台上未回显任何数据。

我是否应该每次想发送数据时都打开一个缓冲写入器,还是一直保持打开状态而永远不关闭它?

我的实际代码-客户端

主要

public class Main {

    public static void main(String args[]) {

        Client chat = new Client("localhost", 6111);
    }
}

客户

公共类客户{

    public Client(String host, int port) {

        SwingUtilities.invokeLater(new Runnable() {

            private Socket chat;

            public void run() {

                try {

                    this.chat = new Socket("localhost", 6113);  

                } catch ( IOException e) {

                    e.printStackTrace();
                }

                Gui gui = new Gui("Chat", this.chat);
            }
        });
    }
}

GUI

public class Gui {

    private JFrame frame;
    private JTextArea area;
    private JTextField field;
    private JMenuBar menu;
    private JButton button;
    private Socket socket;
    private BufferedWriter write;

    public Gui(String title, Socket socket) {

        this.socket = socket;

        try {

            this.write = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));

        } catch (IOException e) {

            e.printStackTrace();
        }

        this.frame = new JFrame(title);
        this.frame.setSize(new Dimension(400, 400));
        this.frame.setLayout(new BorderLayout());
        this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.frame.setResizable(false);

        Elements interfce = new Elements(this.frame);

        this.field = interfce.addField("Texto to send...");
        this.menu = interfce.addBar();
        this.area = interfce.addArea();
        this.button = interfce.addButton("Send");
        this.button.addActionListener(new Listener(this.field, this.socket, this.write));
        this.menu.add(this.field);
        this.menu.add(this.button);
        this.frame.setVisible(true);
    }
}

侦听器(发送数据)

public class Listener implements ActionListener {

    private JTextField text;
    private Socket chat;
    private BufferedWriter writer;

    public Listener(JTextField field, Socket chat, BufferedWriter write) {

        this.text = field;
        this.chat = chat;
        this.writer = write;
    }

    public void actionPerformed(ActionEvent e) {

        System.out.println(this.text.getText());

        try {

            writer.write("Hello\n");
            writer.flush();

        } catch (IOException e1) {

            e1.printStackTrace();
        }
    }
}

和服务器

public class Main {

    public static void main(String args[]) {

        Server chat = new Server(6113);
    }
}

public class Server {

    private int port;
    private ServerSocket server;

    public Server(int port) {

        this.port = port;
        startServer();
    }

    public void startServer() {

        try {

            this.server = new ServerSocket(this.port);
            System.out.println("Starting chat server at port " + this.port + "...");

            while (true) {

                Socket s = this.server.accept();
                System.out.println("Client connected - " + s.getLocalAddress().getHostName());
                Thread client = new Thread(new Client(s));
                client.start();
            }

        } catch (IOException e) {

            System.out.println("Error found!");
            e.printStackTrace();
        }
    }
}


public class Client implements Runnable {

    private Socket client;

    public Client(Socket client) {

        this.client = client;
    }

    public void run() {

        try {

            BufferedReader read = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
            System.out.println("Client says - " + read.readLine());

        } catch (IOException e) {

            e.printStackTrace();
        }
    }
}

我是否应该在每次客户端GUI发送消息时打开或关闭连接,或者一次打开连接并保持打开状态?

客户端和服务器之间的连接通常在整个消息传递会话中都是打开的,而不会为发送每条消息而重新创建。 因此,请保持打开状态,直到客户端或服务器消失。

查看接受连接后在服务器中start Client线程。

public void run() {

    try {

        BufferedReader read = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
        System.out.println("Client says - " + read.readLine());

    } catch (IOException e) {

        e.printStackTrace();
    }
}

这会给您提示吗? 好吧-您必须在run()安排某种形式的循环-监听来自该客户端的更多输入。

做些改变

服务器端:

public void run() {

    try {
        BufferedReader read = new BufferedReader(new InputStreamReader(
                this.client.getInputStream()));
        while (true) {
            System.out.println("Client says - " + read.readLine());
        }
    } catch (IOException e) {

        e.printStackTrace();
    }
}

客户端:

使用PrintWriter而不是提供打印新行功能和自动刷新属性的BufferedWriter

this.write = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream()),
                true);

 ....

public void actionPerformed(ActionEvent e) {

    System.out.println(this.text.getText());

    try {
        writer.write(this.text.getText());
        writer.println();
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM