Java教程

JAVA TCP结合线程使用

本文主要是介绍JAVA TCP结合线程使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package Inter;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServeDemo {
    public static void main(String[] args) throws IOException {
       ServerSocket ss = new ServerSocket(10000);
       while (true){
           Socket s = ss.accept();
           new Thread(new ServerThread(s)).start();
       }

    }
}
package Inter;

import java.io.*;
import java.net.Socket;

public class ServerThread implements Runnable {
    private Socket s;
    public ServerThread(Socket s) {
    this.s = s;
    }

    @Override
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            int count = 0;
            File file = new File("./cc_" + count + ".txt");
            while (file.exists()){
                count++;
                file = new File("./cc_" + count + ".txt");
            }
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            String line;
            while ((line=br.readLine()) != null){
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
            BufferedWriter brw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            brw.write("文件上传成功!");
            brw.newLine();
            brw.flush();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
package Inter;

import java.io.*;
import java.net.Socket;


public class ClientDemo {
    public static void main(String[] args) throws IOException {
        Socket s = new Socket("127.0.0.1",10000);
//
        BufferedReader br = new BufferedReader(new FileReader("./1.txt"));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        String line;
        while ((line=br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        s.shutdownOutput();
        BufferedReader bu = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line1 = bu.readLine();
        System.out.println("服务器反馈:"+line1);
        bu.close();
        bw.close();
        br.close();
    }
}

 

这篇关于JAVA TCP结合线程使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!