实现多线程并发访问上传客户端及代码实现

上传客户端源代码

package blog.seif.net.tcp.uploadtest;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;


public class UploadTestClient {


public static void main(String[] args) throws IOException {
// TODO 自动生成的方法存根


System.out.println("Client on");
Socket s = new Socket("192.168.1.100", 12315);


OutputStream out = s.getOutputStream();


BufferedReader bufr = new BufferedReader(new FileReader("d:\\tempfile\\3.txt"));


PrintWriter pw = new PrintWriter(out, true);


String line = null;
while ((line = bufr.readLine()) != null) {
pw.println(line);
}
// 给服务器端发送结束标记
s.shutdownOutput();
// pw.println("over");


BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));


String strIn = bufIn.readLine();// 阻塞式方法
System.out.println(strIn);


bufr.close();
s.close();


}


}



上传服务器源代码

package blog.seif.net.tcp.uploadtest;


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


public class UploadTestServer {


public static void main(String[] args) throws IOException {
// TODO 自动生成的方法存根
ServerSocket ss = new ServerSocket(12315);


while (true) {
System.out.println("server on");


Socket s = ss.accept();


new Thread(new UpServer(s)).start();


}
}
}


服务器多线程类

package blog.seif.net.tcp.uploadtest;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;


public class UpServer implements Runnable {


private Socket s;


public UpServer(Socket s) {
super();
this.s = s;
}


@Override
public void run() {
// TODO 自动生成的方法存根


String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "....connected");


BufferedReader bufIn;
try {
bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bufOut = new BufferedWriter(new FileWriter("d:\\tempfile\\tcp.txt"));


String line = null;
while ((line = bufIn.readLine()) != null) {
// if("over".equals(line)){
// break;
// }
bufOut.write(line + "\r\n");
bufOut.flush();
System.out.println(line);
}
// fankui
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);


pw.println("upload ok");


bufOut.close();
s.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}


}


}

你可能感兴趣的:(JAVA,网络通信)