TCP socket 简单实现

client:

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.CharBuffer;
import java.util.Timer;
import java.util.TimerTask;

public class Client {
    private String host = "127.0.0.1";
    private int port = 8888;
    private boolean isRecevice = false;

    /**
     * 数据发送线程
     */
    class SendThread implements Runnable {
        private Socket socket;

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

        public void run() {
            while (true) {
                try {
                    send(socket);
                    Thread.sleep(2000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class MyThread implements Runnable {
        private Socket socket;

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

        public void run() {
            try {
                // socket.setKeepAlive(true);
                // socket.setSoTimeout(10);
                while (true) {
                    socket.sendUrgentData(0xFF); // 发送心跳包
                    System.out.println("目前是处于链接状态!");
                    Thread.sleep(3 * 1000);// 线程睡眠3秒
                }
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 数据接收线程
     */
    class ReceiveThread extends Thread {
        private Socket socket;

        public ReceiveThread(Socket socket) {
            this.socket = socket;
            socket.isConnected();
        }

        public void run() {
            while (true) {
                try {
                    recevice(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Socket connect() throws UnknownHostException, IOException {
        Socket socket = new Socket(host, port);// 创建Socket
        return socket;
    }

    private void start() {
        try {
            Socket socket = connect();
            // new Thread(new SendThread(socket)).start();// 启动读线程
            // new Thread(new MyThread(socket)).start();
            ReceiveThread thread = new ReceiveThread(socket);
            thread.start();// 启动收线程
        } catch (Exception e) {
            System.out.println("连接错误");
            e.printStackTrace();
        }
        // 定时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                if (!isRecevice) {
                    try {
                        connect();
                    } catch (UnknownHostException e) {
                        System.out.println("host 错误");
                        e.printStackTrace();
                    } catch (IOException e) {
                        System.out.println("io操作错误");
                        e.printStackTrace();
                    }
                }
            }
        }, 12000);// 设定指定的时间time,此处为2000毫秒
    }

    public void send(Socket socket) throws IOException {
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(
                socket.getOutputStream()));
        pw.write("this is client");
        pw.flush();
    }

    public void recevice(Socket socket) throws IOException {
        Reader reader = new InputStreamReader(socket.getInputStream());
        CharBuffer charBuffer = CharBuffer.allocate(8192);
        int charIndex = -1;
        while ((charIndex = reader.read(charBuffer)) != -1) {
            isRecevice = true;
            send(socket);
            charBuffer.flip();
            System.out.println("client--> " + charBuffer.toString());
        }
    }

    public static void main(String[] args) {
        new Client().start();

    }
}

server:

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.CharBuffer;


public class Server {

    private ServerSocket serverSocket;
    private Socket socket;
    private int port = 5055;

    private void start() throws Exception {
        serverSocket = new ServerSocket(port);
        while (true) {
            socket = serverSocket.accept();
            new Thread(new SocketThread(socket)).start();// 多线程阻塞
        }
    }
    /**
     * 处理socket连接s
     */
    class SocketThread implements Runnable {
        private Socket socket;
        private String temp = "";

        public SocketThread(Socket socket) {
            this.socket = socket;
        }
        public void run() {
            try {
                Reader reader = new InputStreamReader(socket.getInputStream());
                Writer writer = new OutputStreamWriter(socket.getOutputStream());
                CharBuffer charBuffer = CharBuffer.allocate(1024);
                int readIndex = -1;
                while ((readIndex = reader.read(charBuffer)) != -1) {
                    charBuffer.flip();
                    temp += charBuffer.toString();
                    System.out.println("server-->" + temp);
                    writer.write("this is server");
                    writer.flush();

                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    if (!socket.isClosed()) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }

    }

    public static void main(String[] args) {
        Server s = new Server();
        try {
            s.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

你可能感兴趣的:(TCP socket 简单实现)