日期:2014-05-20 浏览次数:20850 次
/*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();
}
}
}
/*自己定义的两个异常,可忽略*/
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, ParserConfigurationException, SAXException, TransformerFactoryConfigurationError, TransformerException {
String fileName = "xmldata3.xml";
File file = new File(fileName);
if(!file.exists() && file.isFile()){