文件上传的小例子

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class FileClient {
private String ip = "localhost";// 设置成服务器IP
private int port = 10000;
private String sendMessage = "C:\\1.gif";
Socket socketConnection = null;
DataOutputStream sendMsg = null;
DataInputStream getMsg = null;
public static void main(String arg[]) throws Exception {
FileClient clientTest = new FileClient();
clientTest.setUpConnection();
clientTest.getMessage();
clientTest.sendMessage();
}
public void setUpConnection() {
try {
socketConnection = new Socket(ip, port);
sendMsg = new DataOutputStream(socketConnection.getOutputStream());
getMsg = new DataInputStream(new BufferedInputStream(
socketConnection.getInputStream()));
} catch (UnknownHostException e) {
System.out.println("连接错误: 未知主机 " + sendMessage + ":" + port);
} catch (IOException e) {
System.out.println("连接时出错: " + e);
}
}
private void sendMessage() throws Exception {
try {
File fi = new File(sendMessage);

System.out.println("文件长度:" + (int) fi.length());
DataInputStream fis = new DataInputStream(new BufferedInputStream(
new FileInputStream(sendMessage)));
sendMsg.writeUTF(fi.getName());
sendMsg.flush();
sendMsg.writeLong((long) fi.length());
sendMsg.flush();

int bufferSize = 8192;
byte[] buf = new byte[bufferSize];

while (true) {
int read = 0;
if (fis != null) {
read = fis.read(buf);
}

if (read == -1) {
break;
}
sendMsg.write(buf, 0, read);
}
sendMsg.flush();
fis.close();
// 注意关闭socket链接,不然服务端会等待客户端的数据过来,
// 直到socket超时,导致数据不完整。
socketConnection.close();
System.out.println("文件传输完成");
} catch (Exception e) {
e.printStackTrace();
if (sendMsg != null)
sendMsg.close();
throw e;
} finally {
}
}
private void getMessage() throws Exception {
try {
getMsg = new DataInputStream(new BufferedInputStream(
socketConnection.getInputStream()));
System.out.println(getMsg.readUTF());
} catch (Exception e) {
e.printStackTrace();
if (getMsg != null)
getMsg.close();
System.out.print("接收消息缓存错误\n");
throw e;
}
}
}

 

你可能感兴趣的:(java,C++,c,.net,socket)