java 在 Swing 小程序中使用的套接字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3244400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:57:59  来源:igfitidea点击:

Socket using in a swing applet

javaswingsocketsweb-applications

提问by Inbal

I should made a server & client in Java,based on Swing and gui.I neeed to make somehow a socket that will go from the server to the client and from the client to the server, and will pass some kind of a string.I would like to have later a function that would do several things according to the string that would be in the socket.
For some reason I couldn't find a simple example for code that shows how it's done in a simple way.
Anyone has any simple example or can explain how is it being done?

我应该基于 Swing 和 gui 用 Ja​​va 制作一个服务器和客户端。我需要以某种方式制作一个套接字,从服务器到客户端,从客户端到服务器,并将传递某种字符串。我希望稍后有一个函数可以根据套接字中的字符串做几件事。
出于某种原因,我找不到一个简单的代码示例来展示它是如何以简单的方式完成的。
任何人都有任何简单的例子或可以解释它是如何完成的?

回答by trashgod

Based on this example, here's a simple network client-server pair using Swing. Note some issues related to correct synchronization: The GUI itself is constructed on the event dispatch thread using invokeLater(). In addition, the code relies on the thread safety of append(). Finally, it incorporates a handy tip from the article Text Area Scrolling.

基于此示例,这是一个使用 Swing 的简单网络客户端-服务器对。请注意与正确同步相关的一些问题:GUI 本身是使用invokeLater(). 此外,代码依赖于append(). 最后,它结合了文章Text Area Scrolling 中的一个方便的提示。

Update: In Java 7, append()is no longer marked as thread safe; invokeLater()is used in display()to sequence updates.

更新:在 Java 7 中,append()不再标记为线程安全;invokeLater()用于display()对更新进行排序。

image

图片

package net;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.text.DefaultCaret;

/**
 * A simple network client-server pair
 * @http://stackoverflow.com/questions/3245805
 */
public class Echo implements ActionListener, Runnable {

    private static final String HOST = "127.0.0.1";
    private static final int PORT = 12345;
    private final JFrame f = new JFrame();
    private final JTextField tf = new JTextField(25);
    private final JTextArea ta = new JTextArea(15, 25);
    private final JButton send = new JButton("Send");
    private volatile PrintWriter out;
    private Scanner in;
    private Thread thread;
    private Kind kind;

    public static enum Kind {

        Client(100, "Trying"), Server(500, "Awaiting");
        private int offset;
        private String activity;

        private Kind(int offset, String activity) {
            this.offset = offset;
            this.activity = activity;
        }
    }

    public Echo(Kind kind) {
        this.kind = kind;
        f.setTitle("Echo " + kind);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getRootPane().setDefaultButton(send);
        f.add(tf, BorderLayout.NORTH);
        f.add(new JScrollPane(ta), BorderLayout.CENTER);
        f.add(send, BorderLayout.SOUTH);
        f.setLocation(kind.offset, 300);
        f.pack();
        send.addActionListener(this);
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        DefaultCaret caret = (DefaultCaret) ta.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
        display(kind.activity + HOST + " on port " + PORT);
        thread = new Thread(this, kind.toString());
    }

    public void start() {
        f.setVisible(true);
        thread.start();
    }

    //@Override
    public void actionPerformed(ActionEvent ae) {
        String s = tf.getText();
        if (out != null) {
            out.println(s);
        }
        display(s);
        tf.setText("");
    }

    //@Override
    public void run() {
        try {
            Socket socket;
            if (kind == Kind.Client) {
                socket = new Socket(HOST, PORT);
            } else {
                ServerSocket ss = new ServerSocket(PORT);
                socket = ss.accept();
            }
            in = new Scanner(socket.getInputStream());
            out = new PrintWriter(socket.getOutputStream(), true);
            display("Connected");
            while (true) {
                display(in.nextLine());
            }
        } catch (Exception e) {
            display(e.getMessage());
            e.printStackTrace(System.err);
        }
    }

    private void display(final String s) {
        EventQueue.invokeLater(new Runnable() {
            //@Override
            public void run() {
                ta.append(s + "\u23CE\n");
            }
        });
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            //@Override
            public void run() {
                new Echo(Kind.Server).start();
                new Echo(Kind.Client).start();
            }
        });
    }
}

回答by Sentry

A basic example would be this: (based on tutorial from Socket Programming in Java, by A.P.Rajshekhar)

一个基本的例子是这样的:(基于APRajshekhar 的Socket Programming in Java教程)

public static void main(String[] args) throws
    UnknownHostException, IOException, InterruptedException {

    Thread serverThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                // create the server socket
                ServerSocket server = new ServerSocket(
                    8888, 5, InetAddress.getLocalHost());
                // wait until clients try to connect
                Socket client = server.accept();

                BufferedReader in = new BufferedReader(new
                    InputStreamReader(client.getInputStream()));

                // loop until the connection is closed
                String line;
                while ((line = in.readLine()) != null) {
                    // output what is received
                    System.out.println(line);
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    Thread clientThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                // connect with the server
                Socket s = new Socket(InetAddress.getLocalHost(), 8888);

                // attach to socket's output stream with auto flush turned on
                PrintWriter out = new PrintWriter(s.getOutputStream(), true);

                // send some text
                out.println("Start");
                out.println("End");
                // close the stream
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    // start server
    serverThread.start();
    // wait a bit
    Thread.sleep(1000);
    // start client
    clientThread.start();
}