gpt4 book ai didi

一个简单的Java测试类型服务器

转载 作者:知者 更新时间:2024-03-13 17:20:03 26 4
gpt4 key购买 nike

用Java写的一个极其简单的服务器,该服务器实现一个简单功能:绑定本地端口,等待客户端发起socket套接字连接,接受连接,服务器为该socket连接创建一个线程,在线程中,每隔1秒发送一条简单的时间戳消息:

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MainClass {
    public static void main(String[] args) {
        ServerSocket serverSocket;
        int seq = 0;
        try {
            serverSocket = new ServerSocket(9999);

            while (true) {
                System.out.println("等待连接...");
                final Socket clientSocket = serverSocket.accept();
                System.out.println("接受连接 " + seq);
                System.out.println("-----");

                final int count = seq;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        DataOutputStream dataOutputStream;
                        try {
                            OutputStream os = clientSocket.getOutputStream();
                            dataOutputStream = new DataOutputStream(os);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }

                        while (true) {
                            String msg = count + " 服务器 " + System.currentTimeMillis();
                            try {
                                dataOutputStream.writeUTF(msg);
                                System.out.println("写入数据:" + msg);

                                dataOutputStream.flush();

                                Thread.sleep(1000);
                            } catch (Exception e) {
                                //e.printStackTrace();
                                System.out.println(count + " 连接异常");
                                break;
                            } finally {
                                try {
                                    dataOutputStream.close();
                                    clientSocket.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }).start();

                seq++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行输出:

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com