当前位置:软件学习 > 其它软件 >>

多线程Socket实用例子

//服务器
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class ThreadServer extends Thread {

    private Socket server;
    private BufferedReader reader;
    private PrintWriter writer;

    public ThreadServer(Socket socket) throws IOException {
        server = socket;
        reader = new BufferedReader(new InputStreamReader(
                server.getInputStream()));
        writer = new PrintWriter(new OutputStreamWriter(
                server.getOutputStream()));
        start();
    }

    public void run() {
        try {
            while (true) {
                String str = reader.readLine();
                if (str.equals("END"))
                    break;
                System.out.println("Echoing:" + str);
                writer.println(str);
            }
        } catch (IOException e) {
        } finally {
            try {
                server.close();
            } catch (IOException e) {
            }
        }
    }
}
//客户端
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;


public class ThreadClient extends Thread {

    private Socket client;
    private BufferedReader reader;
    private PrintWriter writer;
    private static int counter = 0;
    private int id = counter++;
    private static int threadcount = 0;

    public  static int getThreadCount() {
        return threadcount;
    }
    public ThreadClient(InetAddress address){
        System.out.println("Making client" + id);
        threadcount ++;
        try{
            client = new Socket(address,MultiJobServer.PORT);
        }catch (IOException e) {
        }
       
        try {
            reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            writer = new PrintWriter(new OutputStreamWriter(client.getOutputStream()),true);
            start();
        } catch (IOException e) {
            try {
                client.close();
            } catch (IOException e2) {
            }
        }
    }
    public void run(){
        try {
            for(int i = 0 ; i < 25 ; i ++){
                writer.println("Client " + id + ":" + i);
                String str = reader.readLine();
                System.out.println(str);
            }
            writer.println("END");
        } catch (Exception e) {
        }finally{
            try {
                client.close();
            } catch (IOException e) {
            }
            threadcount --;
        }
    }
   
}


作者:陈雨晨
补充:软件开发 , 其他 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,