欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

socket客户端给服务端发消息,服务端回复收到实现GU界面化

程序员文章站 2022-05-21 13:48:29
...

最近一直在准备蓝桥省赛跟CCPC,不怎么有空敲java代码,简单敲了个,实现了个大概,美化什么的,有时间再做叭,代码写了很多块,我都快晕了。

socket客户端给服务端发消息,服务端回复收到实现GU界面化

服务端界面实现

package wanfeng;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;

public class mainServer {
    private JPanel panel1;
    private JTextField textField1;
    private JTextField textField2;
    private JButton Run;
    private JTextArea textResult;

    public mainServer() {
        Run.addMouseListener(new MouseAdapter() {
            ServerSocket serverSocket=null;
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                String string=textField1.getText();
                int num=Integer.parseInt(textField2.getText());
                SocketAddress socketAddress=new InetSocketAddress(string,num) ;
                try {
                    serverSocket=new ServerSocket();
                    serverSocket.bind(socketAddress);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                NetPrintStream printStream=new NetPrintStream(System.out, textResult);
                System.setErr(printStream);
                System.setOut(printStream);

                Server2 server2=new Server2(serverSocket);
                server2.start();
            }
        });
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("mainServer");
        frame.setContentPane(new mainServer().panel1);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //frame.setSize(400, 400);
        frame.setMinimumSize(new Dimension(600, 500));//设置好宽高
        frame.setLocationRelativeTo(null);//窗体居中显示
        frame.pack();
        frame.setVisible(true);
    }
}

创建服务端

package wanfeng;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.PublicKey;

public class Server2 extends Thread {
    private ServerSocket ss=null;
    public static int clientcounter=0;
    public Server2(ServerSocket ss)
    {
        this.ss=ss;
    }
    public  void run()
    {
        Socket s= null;
        try {
            while(true) {
                s = ss.accept();
                clientcounter++;
                SockerThread sockerThread = new SockerThread(s, clientcounter);
                sockerThread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(ss!=null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    public static void main(String[] args) {
    }
}

创建线程

package wanfeng;

import javax.xml.crypto.Data;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SockerThread extends Thread {

    private Socket s = null;
    private int clientcounter = 0;

    public SockerThread(Socket s, int clientcounter) {
        this.s = s;
        this.clientcounter = clientcounter;
        System.out.println("有新线程连接了:当前线程数为:" + clientcounter + "线程id:" + currentThread().getId());
    }

    public void run() {
        //InputStream inputStream=null;
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(s.getInputStream(), "GBK"));
             /*inputStream=s.getInputStream();
            byte[] buf=new byte[1024];
            int num=inputStream.read(buf);
            String string = new String(buf,0,num);*/
            String string = "";
            while (((string = bufferedReader.readLine()).equals("")) == false) {
                //SimpleDateFormat sdf=new SimpleDateFormat("yyyy 年 MM月dd日Ea hh时mm分ss秒");
                //Date parseDate = sdf.parse(sdf.format(new Date()));

                System.out.println(DateFormat.getDateTimeInstance(2, 2, Locale.CHINESE).format(new java.util.Date()) + " " + s.getInetAddress().toString() + " : " + string + "  " + "客户端id: " + clientcounter);
                String string1 = "服务端已收到!";
                PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), "GBK"));
                printWriter.println(string1);
                printWriter.flush();
            }
            Server2.clientcounter--;
            System.out.println(clientcounter + "会话结束+线程id" + currentThread().getId());
            s.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


打印流

package wanfeng;

import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.io.OutputStream;
import java.io.PrintStream;

public class NetPrintStream extends PrintStream {

    public JTextComponent textArea;
    public StringBuffer stringBuffer=new StringBuffer();
    public NetPrintStream(OutputStream outputStream,JTextComponent textArea)
    {
        super(outputStream);
        this.textArea=textArea;

    }
    public void write(byte[] buf,int off,int len)
    {
        final String message=new String(buf,off,len);
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                stringBuffer.append(message);
                textArea.setText(stringBuffer.toString());
            }
        });
    }
}

客户端界面`

package wanfeng;

import javax.swing.*;
import javax.xml.crypto.Data;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.net.*;
import java.util.zip.DataFormatException;

public class Client2GUI {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Client2GUI");
        frame.setContentPane(new Client2GUI().t1);
        frame.setMinimumSize(new Dimension(600, 500));//设置好宽高
        frame.setLocationRelativeTo(null);//窗体居中显示
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private JTextField textField1;
    private JTextField textField2;
    private JTextField textField3;
    private JButton 发送Button;
    private JTextArea textArea1;
    private JButton 启动Button;
    private JPanel t1;
    private Socket socket=null;
    public Client2GUI() {

        启动Button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                String remoteName=textField1.getText();
                int remoteNumber=Integer.parseInt(textField2.getText());

                SocketAddress socketAddress=new InetSocketAddress(remoteName,remoteNumber) ;

                NetPrintStream printStream=new NetPrintStream(System.out,textArea1);
                System.setErr(printStream);
                System.setOut(printStream);


                socket=new Socket();
                try {
                    socket.connect(socketAddress);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
        发送Button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);

                String string=textField3.getText();

                try {
                    PrintWriter printWriter=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"GBK"));
                    printWriter.println(string);
                    printWriter.flush();

                    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
                    textArea1.append(bufferedReader.readLine()+"\n");
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}

写的很糙,巨巨勿喷。呜

socket客户端给服务端发消息,服务端回复收到实现GU界面化

相关标签: 前端学习