2008年7月6日星期日

某人的作业,有用的拿走

今天下午五分钟给某人赶制的作业一份,有需要的拿走。
关键字:java socket tcp 文件传输


import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;

/*
* Copyrights (C) 2008 Bearice (Bearice@Gmail.com)
* Release under GNU/GPL Version 2.
*/
/**
*
* @author Bearice
*/
public class FileTransport {

public static void send(String args[]) throws Exception {
String host = args[1];
int port = Integer.parseInt(args[2]);
System.out.printf("Connecting to %s:%d\n", host, port);
Socket socket = SocketFactory.getDefault().createSocket(host, port);
FileInputStream fis = new FileInputStream(args[3]);
int b;
System.out.println("Sending...");
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
while ((b = fis.read()) != -1) {
bos.write(b);
}
bos.close();
}

public static void recv(String args[]) throws Exception {
int port = Integer.parseInt(args[1]);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(args[2]));
System.out.printf("Listening on port %d\n", port);
Socket socket = ServerSocketFactory.getDefault().createServerSocket(port).accept();
int b;
InputStream is = socket.getInputStream();
System.out.println("Recving...");
while ((b = is.read()) != -1) {
bos.write(b);
}
bos.close();
}

public static void main(String[] args) throws Exception {
if (args.length == 4 && args[0].equalsIgnoreCase("send")) {
send(args);
} else if (args.length == 3 && args[0].equalsIgnoreCase("recv")) {
recv(args);
} else {
System.out.println("Usage:");
System.out.println("FileTransport [recv|send <host>] <port> <file>");
}
}
}

2 条评论:

  1. 熊,你的博客访问速度好慢的说,我是说访问的时候好卡……

    回复删除
  2. 如果你可以访问 自己把解析改到ghs.google.com 在hosts

    回复删除