多线程版本的Socket传输

it2022-05-27  76

服务器

public class Server {    public static void main(String[] args)   {        ServerSocket ss = null;        Socket s = null;        try {            ss = new ServerSocket(5210);        } catch (IOException e) {            // TODO 自动生成的 catch 块            e.printStackTrace();        }        while(true) {            try {                s = ss.accept();            } catch (IOException e) {                // TODO 自动生成的 catch 块                e.printStackTrace();            }        Threadds ts = new Threadds(s);        ts.start();        MyThread mt = new MyThread(s);        mt.start();        }    }}

客户端

public class Client {    public static void main(String[] args) {        Socket s= null ;         try {            s = new Socket("localhost", 5210);        } catch (Exception e) {            e.printStackTrace();        }         MyThread mt = new MyThread(s);        mt.start();        Threadds ts = new Threadds(s);        ts.start();    }}

 

public class MyThread extends Thread{    Scanner sca = new Scanner(System.in);    private Socket s = null;    PrintWriter pw = null;    public MyThread() {        // TODO 自动生成的构造函数存根    }    public MyThread(Socket s) {        this.s= s;    }    public void run() {        try {            pw = new PrintWriter(s.getOutputStream());            while(true) {                pw.println(sca.next());                pw.flush();            }        } catch (IOException e) {            e.printStackTrace();        }finally {            pw.close();        }    }}

 

 

public class Threadds extends Thread{    private Socket s = null;    BufferedReader br = null;    public Threadds() {        // TODO 自动生成的构造函数存根    }    public Threadds(Socket s) {        this.s= s;    }        public void run() {        try {            br = new BufferedReader(new InputStreamReader(s.getInputStream()));            while(true){                System.out.println(br.readLine());            }        } catch (IOException e) {            e.printStackTrace();        }finally {            try {                br.close();            } catch (IOException e) {                // TODO 自动生成的 catch 块                e.printStackTrace();            }        }    }}

转载于:https://www.cnblogs.com/xiaosuye/p/9630198.html

相关资源:Socket 多线程文件传输至服务器端 客户端!

最新回复(0)