Socket编程—传输文件
package TCP;
import java.io.*;
import java.net.*;
class ServerThread implements Runnable{
private Socket socket;
public ServerThread(Socket socket) {
this.socket=socket;
}
public void run() {
String ip=socket.getInetAddress().getHostAddress();
int count=1;
try {
File parentFile = new File("D:\\upload\\");
if(!parentFile.exists()) {
parentFile.mkdir();
}
File file = new File(parentFile,ip+"("+count+").jpg");
while(file.exists()) {
file= new File(parentFile,ip+"("+(count++)+").jpg");
}
InputStream in = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buf= new byte[1024];
int len=0;
while((len=in.read(buf))!=-1) {
fos.write(buf,0,len);
}
OutputStream out = socket.getOutputStream();
out.write("上传成功".getBytes());
in.close();
fos.close();
socket.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
public class UploadTCPServer {
public static void main(String[] args) throws Exception{
ServerSocket serverSocket = new ServerSocket(8080);
while(true) {
Socket client=serverSocket.accept();
new Thread(new ServerThread(client)).start();
}
}
}
package TCP;
import java.io.*;
import java.net.*;
import java.net.InetAddress;
public class UploadTCPClient {
public static void main(String[] args) throws Exception {
Socket client = new Socket("110.65.101.22", 8080);
OutputStream out = client.getOutputStream();
FileInputStream fis = new FileInputStream("D:\\222.jpg");
byte[] buf = new byte[1024];
int len = 0;
System.out.println("连接服务器,开始上传");
while ((len = fis.read(buf)) != -1) {
out.write(buf, 0, len);
}
client.shutdownOutput();
InputStream is = client.getInputStream();
byte[] bufMsg = new byte[1024];
int len2 = is.read(bufMsg);
while (len2 != -1) {
System.out.println(new String(bufMsg, 0, len2));
len2 = is.read(bufMsg);
}
out.close();
is.close();
fis.close();
client.close();
}
}