服务器通信篇(Socket)

简介

  1. 服务器监听端口
  2. 客户端与服务器建立连接
  3. 客户端发送数据请求
  4. 服务器业务逻辑处理
  5. 服务器返回信息

在这里插入图片描述



一、服务端

  1. 创建服务端口
  2. 开启服务
  3. 另起一个线程,轮询监听端口
  4. 开启处理客户端请求,轮询请处理求

ServerBoot.java

public class ServerBoot {

    private static final int PORT = 8000;

    public static void main(String[] args) {
        
        Server server = new Server(PORT);
        
        server.start();
    }
}

Server.java

public class Server {

    private ServerSocket serverSocket;

    public Server(int port) {
        try {
            this.serverSocket = new ServerSocket(port);

            System.out.println("服务器启动成功,端口:" + port);
        } catch (IOException e) {
            System.out.println("服务器启动失败");
        }
    }

    public void start() {
        new Thread(new Runnable() {
            public void run() {
                doStart();
            }
        }).start();
    }

    private void doStart() {
        while (true) {
            try {
                Socket client = serverSocket.accept();
                new ClientHandler(client).start();
            } catch (IOException e) {
                System.out.println("服务器端异常");
            }
        }
    }
}



二、客户端

  1. 客户端启动
  2. 另起一个线程,客户端每5秒发送数据

Client.java

public class Client {

    private static final String HOST = "127.0.0.1";
    private static final int PORT = 8000;
    private static final int SLEEP_TIME = 5000;

    public static void main(String[] args) throws IOException {
        final Socket socket = new Socket(HOST, PORT);

        new Thread(new Runnable() {
            public void run() {
                System.out.println("客户端启动成功!");

                while (true) {
                    try {
                        String message = "hello world";
                        System.out.println("客户端发送数据:" + message);
                        socket.getOutputStream().write(message.getBytes());
                    } catch (IOException e) {
                        System.out.println("写数据出错!");
                        e.printStackTrace();
                    }
                    sleep();
                }
            }
        }).start();
    }

    private static void sleep() {
        try {
            Thread.sleep(SLEEP_TIME);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}


三、运行

先启动服务器,再启动客户端

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值