java Socket 双向通信(支持直接通过Telnet连接Server并通信)

Socket Server

package com.xbb.demo.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Socket 服务端
 */
public class SocketServer {
    final static int listenPort = 12345;
    public static void main(String[] args) {
        // 启动服务端
        EchoServer server = new EchoServer(listenPort);
        server.startService();
    }
}
class EchoServer {
    /**
     * 监听端口
     */
    private int port;

    /**
     * 构造方法
     * @param port
     */
    public EchoServer(int port){
        this.port = port;
    }
    // TODO

    /**
     * 启动Server
     */
    public void startService(){
        // 创建一个Server
        ServerSocket server = null;
        try {
            // 实例化
            server = new ServerSocket(port);
            // 循环监听是否有客户端连接进来
            while (true) {
                // 当有客户端连接时创建一个独立的线程与客户端进行对接
                Socket client = server.accept();
                new Thread(new SSocket(client)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (server != null){
                try{
                    server.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

/**
 * 当有一个Client接入时启动一个线程来进行交互
 */
class SSocket implements Runnable {
    /**
     * 客户端
     */
    private Socket client;

    /**
     * 构造方法
     * @param client
     */
    public SSocket(Socket client) {
        this.client = client;
    }

    /**
     * 主方法体
     */
    public void run() {
        // java新特性:把需要关闭的IO可以写到try()中.这样就可以不用再在Finally中关闭了
        try(
                // 接收客户端消息.
                InputStream input = client.getInputStream();
                BufferedReader reader  = new BufferedReader(new InputStreamReader(input));
                // 输出消息给客户端
                OutputStream output = client.getOutputStream();
                PrintWriter writer= new PrintWriter(output);
        ) {
            // 欢迎语
            writer.println(EchoConstant.STR_WELCOME);
            writer.flush();
            String msg = "";
            // 循环与客户端进行交互
            while(true){
                // 读取客户端消息
                msg = reader.readLine();
                // 当接收到bye时结束连接
                if (EchoConstant.STR_BYE_CONSOLE.equals(msg) || EchoConstant.STR_BYE_TELNET.equals(msg)){
                    writer.println(EchoConstant.STR_BYE_BYE);
                    writer.flush();
                    client.close();
                    break;
                }else{
                    // 回复原客户端发过来的消息
                    writer.println(msg);
                    writer.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (client!=null){
                try{
                    client.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

Socket Client

package com.xbb.demo.socket;

import java.io.*;
import java.net.Socket;

/**
 * Socket 客户端
 */
public class SocketClient{
    final static int listenPort = 12345;
    public static void main(String[] args) {
        // 启动客户端
        EchoClient client = new EchoClient(listenPort);
        client.startService();
    }
}

/**
 * Socket 客户端
 */
class EchoClient {
    // TODO
    /**
     * 监听端口
     */
    private int port;

    /**
     * 构造方法
     * @param port
     */
    public EchoClient(int port){
        this.port = port;
    }

    /**
     * 启动服务
     */
    public void startService(){
        // 定义Socket, IO
        // java新特性:把需要关闭的IO可以写到try()中.这样就可以不用再在Finally中关闭了
        try(
                // 实例化客户端,IO
                Socket socket = new Socket(EchoConstant.SERVER_HOST, port);
                // 输出信息给客户端
                OutputStream out = socket.getOutputStream();
                PrintWriter writer= new PrintWriter(out);
                // 接收客户端消息
                InputStream in = socket.getInputStream();
                BufferedReader reader  = new BufferedReader(new InputStreamReader(in));
                ){
            // 读取客户端的欢迎消息
            String ret = reader.readLine();
            System.out.println(ret);
            // 循环读取用户在Console输入的消息并写给服务端
            BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));
            while(true){
                String str = systemIn.readLine();
                writer.println(str);
                writer.flush();
                ret = reader.readLine();
                System.out.println(ret);
                // 收到Bye bye退出
                if (EchoConstant.STR_BYE_BYE.equals(ret)){
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

Telnet 连接服务端

river@RiverJin:~$ telnet 127.0.0.1 12345
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Welcome to My Echo Server
你好
你好
我是你
我是你
你也是我
你也是我
bye
Bye bye
Connection closed by foreign host.
river@RiverJin:~$ 

你可能感兴趣的:(java)