日期:2014-05-20  浏览次数:20805 次

[小白]TCP协议文件传输问题
本帖最后由 lrcry 于 2013-03-31 16:16:52 编辑
我想实现一个TCP协议,C/S模式的文件上传,Server支持多线程;
但是不知为什么,我通过客户端上传上来的文件,到达服务器的时候时好时坏;
意思就是,有的时候Server能接收到完整的文件,但是有的时候,接收到的文件就是空的。而且是空的时候多,是完整文件的时候少。
有源码如下:

服务器端

  /*Server端,多线程接收*/
public class MainBean {
public static void main(String[] args){
/*Init socket*/
try {
System.out.print("Starting server...");
ServerSocket ss = new ServerSocket(10086);
System.out.println("OK");
while(true){
Socket s = ss.accept();
System.out.println("Get TCP connection in: " + s.getInetAddress());
new Thread(new Threads(s)).start();
}
} catch (IOException e1) {
System.out.println("Server init failed!");
}


服务器线程实现

/*Server端,线程Threads.java*/
public class Threads implements Runnable {
private Socket s;

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

@Override
public void run() {
int count = 0;
String ip = s.getInetAddress().getHostAddress();

try {
InputStream in = s.getInputStream();

System.out.print("Creating files on server...");
File file = new File(ip + "(" + count + ").xml");//命名规律

                        /*如果文件已经存在,则重命名为如下格式*/
while(file.exists()){
file = new File(ip + "(" + count++ + ").xml");
}
System.out.println("OK");

                        /*接收*/
System.out.println("Receiving...");
FileOutputStream fOut = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = 0;
while((len = in.read(buf)) != -1){
fOut.write(buf, 0, len);
}
System.out.println("OK");

/*向客户端返回信息*/
OutputStream out = s.getOutputStream();
System.out.println("Server: returning to client..");
out.write("Upload succeed.".getBytes());

fOut.close();
s.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


客户端,上传的文件时xml格式

/*自己定义的两个异常,可忽略*/
class FileNameException extends Exception{
FileNameException(String msg){
super(msg);
}
}
class FileSizeException extends Exception{
FileSizeException(String msg){
super(msg);
}
}

public class UploadClient {

public static void main(String[] args) throws IOException, FileNameException, FileSizeException, ParserConfigurationExceptionSAXException, TransformerFactoryConfigurationError, TransformerException {

String fileName = "xmldata3.xml";
File file = new File(fileName);

if(!file.exists() && file.isFile()){