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

2019年7月5日21:43:25 评论 72

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;
        }
    }
}



 

3.总结

示例代码演示了 Java 怎么实现基于线程的客户端套接字,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: