Java multithreaded TCP server receives messages and returns receipt

It can be seen from the console that each user is assigned a thread, the client sends a message, the server receives the message and if it succeeds, the receipt "received successfully".

Otherwise, the receipt fails.

Client.java

package thread;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Client extends JFrame
{
    static Client ui;
    private JButton st, ex; //按钮
    private static JTextArea text, mes;
    public Client()
    {
        super("Client");
        setSize(670, 300);
        setLocationRelativeTo(null);//居中
        draw();
    }
    public void draw()
    {
        setLayout(null);
        JLabel name = new JLabel("主机:127.0.0.1", JLabel.CENTER);
        name.setFont(new Font("隶书", Font.PLAIN, 20));
        name.setBounds(0, 0, 200, 50);
        JLabel port = new JLabel("端口号:9999", JLabel.CENTER);
        port.setFont(new Font("隶书", Font.PLAIN, 20));
        port.setBounds(200, 0, 120, 50);
        JLabel send = new JLabel("消息", JLabel.CENTER);
        send.setFont(new Font("隶书", Font.PLAIN, 20));
        send.setBounds(150, 50, 120, 50);
        JLabel rec = new JLabel("服务器回执", JLabel.CENTER);
        rec.setFont(new Font("隶书", Font.PLAIN, 20));
        rec.setBounds(480, 50, 120, 50);
        st = new JButton("发送");
        st.setFont(new Font("隶书", Font.PLAIN, 20));
        st.setForeground(Color.BLACK);
        st.setBackground(Color.YELLOW);
        st.setBorderPainted(false);
        ex = new JButton("退出");
        ex.setFont(new Font("隶书", Font.PLAIN, 20));
        ex.setForeground(Color.BLACK);
        ex.setBackground(Color.GREEN);
        ex.setBorderPainted(false);
        st.setBounds(450, 10, 80, 40);
        ex.setBounds(550,10,80, 40);
        text = new JTextArea();
        text.setFont(new Font("隶书", Font.PLAIN, 30));
        text.setBounds(0, 100, 400, 300);
        mes = new JTextArea();
        mes.setFont(new Font("隶书", Font.PLAIN, 30));
        mes.setBounds(440, 100, 220, 300);
        st.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent a) {
                if (a.getButton() == a.BUTTON1) {
                    try
                    {
                        Thread w = new Thread();
                        w.start();
                        send();
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
            public void mousePressed(MouseEvent a) {}
            public void mouseReleased(MouseEvent a) {}
            public void mouseEntered(MouseEvent a) {}
            public void mouseExited(MouseEvent a) {}
        });
        ex.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent a) {
                if (a.getButton() == a.BUTTON1) {
                    System.exit(0);
                }
            }
            public void mousePressed(MouseEvent a) {}
            public void mouseReleased(MouseEvent a) {}
            public void mouseEntered(MouseEvent a) {}
            public void mouseExited(MouseEvent a) {}
        });
        add(name);
        add(port);
        add(st);
        add(ex);
        add(send);
        add(text);
        add(rec);
        add(mes);
        setVisible(true);
    }

    public static void send() throws IOException
    {
        String s = ui.text.getText();
        Socket now = new Socket("127.0.0.1", 9999);
        OutputStream out = now.getOutputStream();
        out.write(s.getBytes());
        out.close();
        now.close();
        recv();
    }
    public static void recv() throws IOException
    {
        ServerSocket s = new ServerSocket(10000);
        Socket x = s.accept();
        InputStream in = null;
        try {
            in = x.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        int num = 0;
        byte[] u = new byte[1024];
        StringBuffer res1 = new StringBuffer();
        while (true)
        {
            try
            {
                if (!((num = in.read(u)) != -1)) break;
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            res1.append(new String(u, 0, num));
        }
        res1.append('\n');
        mes.setText(String.valueOf(res1));
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        s.close();
        x.close();
    }
    public static void main(String[] args) throws IOException, IOException
    {
        ui = new Client();
    }
}

 ServerThread.java

package thread;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

class ServerThread extends Thread
{
    private Socket s = null;
    public String res;
    private int cnt;
    public ServerThread(Socket s, int cnt)
    {
        this.s = s;
        this.cnt = cnt;
        start();
    }
    public void run()
    {
        System.out.println("当前线程: " + Thread.currentThread().getId() + " 当前用户: " + cnt);
        InputStream in = null;
        try {
            in = s.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        int num = 0;
        byte[] u = new byte[1024];
        StringBuffer res1 = new StringBuffer();
        while (true)
        {
            try
            {
                if (!((num = in.read(u)) != -1)) break;
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            res1.append(new String(u, 0, num));
        }
        res1.append('\n');
        this.res = new String(res1);
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

TCPServer.java

package thread;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

class TcpServer implements Runnable
{
    private static int cnt;
    public String res;
    public ServerSocket ss;
    public void run()
    {
        try
        {
            ++cnt;
            Socket s = ss.accept();
            ServerThread st = new ServerThread(s, cnt);
            st.join();
            this.res = st.res;
        } catch (IOException | InterruptedException e)
        {
            e.printStackTrace();
        };

    }
    public static void send(String s) throws IOException
    {
        Socket now = new Socket("127.0.0.1", 10000);
        OutputStream out = now.getOutputStream();
        out.write(s.getBytes());
        out.close();
        now.close();
    }
}

 UI.java

package thread;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.net.ServerSocket;

public class UI extends JFrame
{
    public String res;
    private static ServerSocket ss;
    public static JTextArea text;
    public UI() throws IOException, InterruptedException
    {
        super("TcpServe");
        setSize(970, 600);
        setLocationRelativeTo(null);//居中
        draw();
    }
    public void draw() throws IOException, InterruptedException
    {
        setLayout(null);
        JLabel name = new JLabel("服务器:admin", JLabel.CENTER);
        name.setFont(new Font("隶书", Font.PLAIN, 20));
        name.setBounds(0, 0, 120, 50);
        JLabel port = new JLabel("端口号:9999", JLabel.CENTER);
        port.setFont(new Font("隶书", Font.PLAIN, 20));
        port.setBounds(160, 0, 120, 50);
        JButton st, ex; //按钮
        st = new JButton("启动");
        st.setFont(new Font("隶书", Font.PLAIN, 20));
        st.setForeground(Color.BLACK);
        st.setBackground(Color.YELLOW);
        st.setBorderPainted(false);
        ex = new JButton("退出");
        ex.setFont(new Font("隶书", Font.PLAIN, 20));
        ex.setForeground(Color.BLACK);
        ex.setBackground(Color.GREEN);
        ex.setBorderPainted(false);
        st.setBounds(750, 10, 80, 40);
        ex.setBounds(850,10,80, 40);
        text = new JTextArea();
        text.setFont(new Font("隶书", Font.PLAIN, 30));
        text.setBounds(0, 80, 970, 500);
        add(name);
        add(port);
        add(st);
        add(ex);
        add(text);
        st.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent a) {
                if (a.getButton() == a.BUTTON1) {
                        System.out.println("已启动");
                }
            }
            public void mousePressed(MouseEvent a) {}
            public void mouseReleased(MouseEvent a) {}
            public void mouseEntered(MouseEvent a) {}
            public void mouseExited(MouseEvent a) {}
        });
        ex.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent a) {
                if (a.getButton() == a.BUTTON1) {
                    System.exit(0);
                }
            }
            public void mousePressed(MouseEvent a) {}
            public void mouseReleased(MouseEvent a) {}
            public void mouseEntered(MouseEvent a) {}
            public void mouseExited(MouseEvent a) {}
        });
        setVisible(true);
        execute();
    }
    public void execute() throws IOException, InterruptedException
    {
        TcpServer now = new TcpServer();
        ss = new ServerSocket(9999);
        StringBuffer pr = new StringBuffer();
        int cnt = 1;
        while (true)
        {
            now.ss = ss;
            now.run();
            if (now.res.length() == 1)
            {
                now.send("接收失败");
                continue;
            }
            else
                now.send("接收成功");
            pr.append("用户" + String.valueOf(cnt) + ":" + now.res);
            ++cnt;
            text.setText(String.valueOf(pr));
        }
    }
    public static void main(String[] args) throws IOException, InterruptedException
    {
        UI now = new UI();
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_43731933/article/details/109033023