TCP and UDP simple example

Simple TCP example

TCP server

/**
 * @CalssName TcpServer
 * @Description tcp服务端
 * @since JDK 1.8
 */
public class TcpServer {

    private ServerSocket serverSocket;
    private int port = 8090;

    public TcpServer() throws IOException {
        this.serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务端启动....");
        try (
                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
        ) {
            while (true) {
                String msg = bufferedReader.readLine();
                System.out.println("收到消息:" + msg);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpServer tcpServer = new TcpServer();
        tcpServer.start();
    }
}

TCP Client

/**
 * @CalssName TcpClient
 * @Description tcp客户端
 * @since JDK 1.8
 */
public class TcpClient {
    private Socket socket;
    private String connectHost = "localhost";
    private int connectPort = 8090;

    public TcpClient() throws IOException {
        this.socket = new Socket(connectHost, connectPort);
    }

    public void send() throws IOException {
        System.out.println("客户端启动...");
        try (
                Socket stk = this.socket;
                OutputStream outputStream = stk.getOutputStream();
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "utf-8");
                PrintWriter printWriter = new PrintWriter(outputStreamWriter, true)
        ) {
            Scanner sc = new Scanner(System.in);
            while (true) {
                printWriter.println(sc.nextLine());
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpClient tcpClient = new TcpClient();
        tcpClient.send();
    }
}

Easy to use TCP chat room

Server

/**
 * @CalssName TcpServer
 * @Description tcp服务端
 * @since JDK 1.8
 */
public class TcpServer {

    private ServerSocket serverSocket;
    private int port = 8090;

    private List<PrintWriter> printWriters;

    public TcpServer() throws IOException {
        this.serverSocket = new ServerSocket(port);
        this.printWriters = Collections.synchronizedList(new ArrayList<>());
    }

    public void start() throws IOException {
        System.out.println("服务启动....");
        try (ServerSocket serSocket = this.serverSocket) {
            for (; ; ) {
                Socket socket = serSocket.accept();
                System.out.println("链接成功:" + socket);
                new Thread(new ForwardingMsgRunnable(this.printWriters, socket)).start();
            }
        }
    }

    //转发消息到所有客户端线程
    class ForwardingMsgRunnable implements Runnable {
        private List<PrintWriter> printWriters;
        private Socket socket;
        private PrintWriter printWriter;

        public ForwardingMsgRunnable(List<PrintWriter> printWriters, Socket socket) throws IOException {
            this.printWriters = printWriters;
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
            this.printWriter = new PrintWriter(outputStreamWriter, true);
            this.printWriters.add(printWriter);
            this.socket = socket;
        }

        @Override
        public void run() {
            try (
                    Socket skt = this.socket;
                    InputStream inputStream = skt.getInputStream();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                    BufferedReader br = new BufferedReader(inputStreamReader);
            ) {
                String msg = "1";
                while (msg != null) {
                    msg = br.readLine();
                    if (msg != null) {
                        //用索引遍历,别的线程remove没问题
                        for (int i = 0; i < this.printWriters.size(); i++) {
                            this.printWriters.get(i).println(msg);
                        }
                    } else {
                        this.printWriters.remove(this.printWriter);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpServer tcpServer = new TcpServer();
        tcpServer.start();
    }
}

Client

/**
 * @CalssName TcpClient
 * @Description tcp客户端
 * @since JDK 1.8
 */
public class TcpClient {
    private Socket socket;
    private String connectHost = "localhost";
    private int connectPort = 8090;

    public TcpClient() throws IOException {
        this.socket = new Socket(connectHost, connectPort);
    }

    public void send() throws IOException {
        System.out.println("客户端启动...");
        //给服务器发消息
        try (
                Socket skt = this.socket;
                OutputStream outputStream = skt.getOutputStream();
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "utf-8");
                PrintWriter printWriter = new PrintWriter(outputStreamWriter, true);
                Scanner sc = new Scanner(System.in);
        ) {
            System.out.print("用户名:");
            String username = sc.nextLine();
            //接收消息处理
            new Thread(new ShowMsgRunnable(this.socket)).start();
            while (!skt.isClosed()) {
                String inStr = sc.nextLine();
                if ("exit".equals(inStr)) break;
                printWriter.println(username + ":" + inStr);
            }
            System.out.println("exiting...");
        }
    }

    //显示消息
    class ShowMsgRunnable implements Runnable {

        private Socket socket;

        public ShowMsgRunnable(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (
                    Socket skt = this.socket;
                    InputStreamReader inputStreamReader = new InputStreamReader(skt.getInputStream());
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            ) {
                System.out.println("显示消息:");

                while (!skt.isClosed()) {
                    String msg = bufferedReader.readLine();
                    System.out.println(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpClient tcpClient = new TcpClient();
        tcpClient.send();
    }
}

Simple UDP example

Server

/**
 * @CalssName udpServer
 * @Description Udp服务端
 * @since JDK 1.8
 */
public class UdpServer {
    private DatagramSocket server;

    public UdpServer() throws SocketException {
        this.server = new DatagramSocket(8060);
    }

    public void start() {

        System.out.println("服务端启动...");
        DatagramPacket datagramPacket = new DatagramPacket(new byte[32], 32);

        try (DatagramSocket datagramSocket = this.server) {
            datagramSocket.receive(datagramPacket);
            byte[] bytes = datagramPacket.getData();
            System.out.println("收到数据:" + new String(bytes, "utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        new UdpServer().start();
    }
}

Client

/**
 * @CalssName UdpClient
 * @Description Udp客户端
 * @since JDK 1.8
 */
public class UdpClient {

    private DatagramSocket client;

    public UdpClient() throws SocketException {
        this.client = new DatagramSocket();
    }

    public void start() {
        try (

                DatagramSocket datagramSocket = this.client;
        ) {
            String msg = "hello server,I am udp client...";
            DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes("utf-8"), msg.length(), InetAddress.getByName("localhost"), 8060);
            datagramSocket.send(datagramPacket);
        } catch (UnsupportedEncodingException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws SocketException {
        new UdpClient().start();
    }
}

Guess you like

Origin www.cnblogs.com/yhongyin/p/11117722.html