Java 怎么实现基于线程的客户端套接字

2019年7月5日21:43:25Java 怎么实现基于线程的客户端套接字已关闭评论 432 717字阅读2分23秒

1.简介

Java 怎么实现基于线程的客户端套接字?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
import java.io.*;
import java.net.*;
import java.util.*;

public class Client extends Thread {
    Socket clientSocket = null;

    public Client(Socket s) {
        clientSocket = s;
    }

    public void run() {
        if (clientSocket == null) {
            return;
        }

        PrintStream out = null;

        System.out.println("creating output stream");

        try {
            out = new PrintStream(clientSocket.getOutputStream());
        } catch (IOException e) {
            System.err.println("Error binding output to socket, " + e);
            System.exit(1);
        }

        System.out.println("writing current date");

        Date d = new Date();
        out.println(d);

        try {
            out.close();
            clientSocket.close();
        } catch (IOException e) {
        }
    }

    protected void finalize() {
        if (clientSocket != null) {
            try {
                clientSocket.close();
            } catch (IOException e) {
            }
            clientSocket = null;
        }
    }
}



 
编程十万个怎么办