在 Swing 小程序中使用的套接字 [英] Socket using in a swing applet

查看:19
本文介绍了在 Swing 小程序中使用的套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

基于这个

包网;导入 java.awt.*;导入 java.awt.event.*;导入 java.io.*;导入 java.net.*;导入 java.util.Scanner;导入 javax.swing.*;导入 javax.swing.text.DefaultCaret;/*** 一个简单的网络客户端-服务器对* @http://stackoverflow.com/questions/3245805*/公共类 Echo 实现 ActionListener、Runnable {private static final String HOST = "127.0.0.1";私有静态最终 int 端口 = 12345;私有最终 JFrame f = new JFrame();私人最终 JTextField tf = 新 JTextField(25);私人最终 JTextArea ta = 新 JTextArea(15, 25);private final JButton send = new JButton("Send");私有 volatile PrintWriter 输出;私人扫描仪;私有线程线程;私人种类;公共静态枚举种类{客户端(100,尝试"),服务器(500,等待");私有整数偏移量;私人字符串活动;私人种类(整数偏移,字符串活动){this.offset = 偏移量;this.activity = 活动;}}公共回声(种类){this.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());}公共无效开始(){f.setVisible(true);线程开始();}//@覆盖public void actionPerformed(ActionEvent ae) {字符串 s = tf.getText();如果(出!= null){out.println(s);}显示器;tf.setText("");}//@覆盖公共无效运行(){尝试 {插座插座;if (kind == Kind.Client) {套接字 = 新套接字(主机,端口);} 别的 {ServerSocket ss = new ServerSocket(PORT);套接字 = ss.accept();}in = new Scanner(socket.getInputStream());out = new PrintWriter(socket.getOutputStream(), true);显示(已连接");而(真){显示(in.nextLine());}} 捕获(异常 e){显示(e.getMessage());e.printStackTrace(System.err);}}私有无效显示(最终字符串){EventQueue.invokeLater(new Runnable() {//@覆盖公共无效运行(){ta.append(s + "\u23CE\n");}});}公共静态无效主(字符串 [] args){EventQueue.invokeLater(new Runnable() {//@覆盖公共无效运行(){新的 Echo(Kind.Server).start();新 Echo(Kind.Client).start();}});}}

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?

解决方案

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.

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

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

这篇关于在 Swing 小程序中使用的套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆