Java----TCP上传文件多线程版
作者:
Agoni7z
,
2024-05-08 11:02:09
,
所有人可见
,
阅读 15
Client
package com.text.A07text.text2;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 10000);
// 2.读取本地文件并写入服务器中
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("untitled\\src\\com\\text\\A07text\\text2"));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
// 往服务器写出结束标记
socket.shutdownOutput();
// 接收服务器的回写数据
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = br.readLine();
System.out.println(line);
socket.close();
}
}
Server
package com.text.A07text.text2;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10000);
while (true) {
Socket socket = ss.accept();
// 开启一条线程
// 一个用户对应服务端的一条线程
new Thread(new MyRunnable(socket)).start();
}
}
}
Myrunnable
package com.text.A07text.text2;
import java.io.*;
import java.net.Socket;
public class MyRunnable implements Runnable {
Socket socket;
public MyRunnable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("untitled\\src\\com\\text\\A07text\\text2\\微信图片_20240310191552.jpg"));
int len;
byte[] bytes = new byte[1024];
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
//回写数据
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write("上传成功");
bw.newLine();
bw.flush();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//5. 释放资源
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}