server端
package com.hjb.version.tcp;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hjb.version.util.Constant;
public class TcpServer {
public class SocketThread extends Thread {
public void run() {
try {
ServerSocket server = new ServerSocket(Constant.getServer_port());
Socket socket = new Socket();
while (true) {
socket = server.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
byte[] b = new byte[1024];
// 1、得到文件名
int a = is.read(b);
String filename = new String(b, 0, a);
System.out.println("接受到的文件名为:" + filename);
FileOutputStream fos = new FileOutputStream(Constant.getUploadPath() + "\\" + filename);
int length = 0;
while ((length = is.read(b)) != -1) {
// 2、把socket输入流写到文件输出流中去
fos.write(b, 0, length);
}
// fos.flush();
fos.close();
os.flush();
os.close();
is.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TcpServer.SocketThread socketThread = new TcpServer().new SocketThread();
socketThread.start();
}
}
client端
package com.hjb.version.tcp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import com.hjb.version.util.Constant;
public class TcpClient {
public static void SendTcpTextData(String HostName, int HostPort,
String filePath) throws IOException {
try {
Socket client = new Socket(HostName, HostPort);
InputStream is = client.getInputStream();
OutputStream os = client.getOutputStream();
File file = new File(filePath);
String filename = file.getName();
System.out.println("send's file name:"+filename);
//1、发送文件名
os.write(filename.getBytes());
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length = 0;
while((length=fis.read(b))!=-1){
//2、把文件写入socket输出流
os.write(b, 0, length);
}
os.close();
fis.close();
is.close();
System.out.println("send over");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) throws IOException {
SendTcpTextData(Constant.getServer_host(),Constant.getServer_port(), "E:\\cc_10.rar");
}
}