简体   繁体   English

Java服务器客户端网络

[英]Java server client networking

Should I open - close the connection each time my client GUI sends a message or open a connection one time and keep it open ? 我是否应该在每次客户端GUI发送消息时打开或关闭连接,或者一次打开连接并保持打开状态?

Im sending data using BufferedWriter but this methid just seems to work for one time only, after doing the write and the flush method Im able just to send 1 message to my server, then it just doesnt get the data im sending... 我使用BufferedWriter发送数据,但此方法似乎只工作一次,执行了写入和刷新方法后,我只能向我的服务器发送1条消息,然后它没有收到正在发送的数据...

Client connects - sends data to server (1st time) - Works Client sends data again - no data echoed on server console. 客户端连接-将数据发送到服务器(第一次)-Works客户端再次发送数据-服务器控制台上未回显任何数据。

Should I open a bufferedwriter each time I want to send data or keep one open all the time and never close it? 我是否应该每次想发送数据时都打开一个缓冲写入器,还是一直保持打开状态而永远不关闭它?

My actual code - Client side 我的实际代码-客户端

Main 主要

public class Main {

    public static void main(String args[]) {

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

Client 客户

public class Client { 公共类客户{

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

Listener (sends data) 侦听器(发送数据)

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

And the server 和服务器

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

Should I open - close the connection each time my client GUI sends a message or open a connection one time and keep it open ? 我是否应该在每次客户端GUI发送消息时打开或关闭连接,或者一次打开连接并保持打开状态?

Connection between a Client and Server is generally open for the entire session of messaging and not recreated for sending each message. 客户端和服务器之间的连接通常在整个消息传递会话中都是打开的,而不会为发送每条消息而重新创建。 So keep it open until the client or the Server has to go away. 因此,请保持打开状态,直到客户端或服务器消失。

Look at your Client thread that you start in your server upon accepting a Connection. 查看接受连接后在服务器中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();
    }
}

Does this give you a hint ? 这会给您提示吗? Well - you have to arrange for some sort of looping here within your run() - listening for more inputs from that client. 好吧-您必须在run()安排某种形式的循环-监听来自该客户端的更多输入。

Just do some changes 做些改变

Server side: 服务器端:

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

Client side: 客户端:

use PrintWriter instead of BufferedWriter that provide print new line functionality and auto flush property. 使用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