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

x33g5p2x  于2022-05-19 转载在 Java  
字(1.2k)|赞(0)|评价(0)|浏览(296)

用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();
        }
    }
}

运行输出:

相关文章

最新文章

更多