黑马程序员技术交流社区
标题:
每日送分一题··
[打印本页]
作者:
攻城狮
时间:
2012-5-18 18:48
标题:
每日送分一题··
使用TCP协议写一个可以上传文件的服务器和客户端。
要求客户端通过键盘录入获取任意文件,服务端原样保存。
代码清晰、简洁 写出解题思路和重要方法备注
作者:
刘克方
时间:
2012-5-18 19:54
本帖最后由 刘克方 于 2012-5-18 20:44 编辑
//客户端
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ObjectInputStream.GetField;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
//要上传的文件
if(args.length==0){
System.out.println("请输入您要上传的文件路径");
return;
}
File file=new File(args[0]);
uploadFile(file);
}
protected static void uploadFile(File filepath) {
BufferedInputStream buffer=null;
FileInputStream filein=null;
OutputStream out=null;
Socket socket=null;
try {
socket=new Socket("127.0.0.1",7789);
out=socket.getOutputStream();
filein=new FileInputStream(filepath);
buffer=new BufferedInputStream(filein);
//发送文件名
out.write(filepath.getName().getBytes());
byte[] byt=new byte[1024];
int len=0;
//让线程睡眠一秒,等文件名发送以后,再继续发送文件内容
Thread.sleep(1000);
//发送文件内容
while((len=buffer.read(byt))!=-1){
out.write(byt,0,len);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(buffer!=null){
try {
buffer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(filein!=null){
try {
filein.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//服务器端
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
final ServerSocket server=new ServerSocket(7789);
while(true){
System.out.println("等待连接");
Socket socket=server.accept();
System.out.println("某客户端已连接连接");
//文件保存地址
File savepath=new File("D://");
startUpload(socket,savepath);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void startUpload(final Socket socket,final File savePath) throws IOException {
//开启一个新线程进行上传
new Thread(new Runnable() {
public void run() {
InputStream in=null;
FileOutputStream out=null;
BufferedOutputStream buffer=null;
try {
in=socket.getInputStream();
//获取文件名
byte[] namebuffer=new byte[100];
int namelen=in.read(namebuffer);
String fileName=new String(namebuffer,0,namelen);
System.out.println(fileName);
//文件保存路径
out=new FileOutputStream(savePath+"/"+fileName);
buffer=new BufferedOutputStream(out);
//获取文件内容
byte[] byt=new byte[1024];
int len=0;
while((len=in.read(byt))!=-1){
System.out.println(new String(byt,0,len));
buffer.write(byt,0,len);
}
System.out.println("文件上传成功,请到"+savePath+"目录下查看");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(in!=null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(buffer!=null){
try {
buffer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}).start();
}
}
作者:
林豪
时间:
2012-5-18 20:19
本帖最后由 林豪 于 2012-5-18 20:26 编辑
import java.net.*;
import java.io.*;
class TransClient
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.1.55",12345); //创建一个客户端,目标是192.168.1.55:12345
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); //读取键盘
BufferedWriter bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while((line=bufr.readLine())!=null) //以下是读取键盘然后发送到服务端
{
bufOut.write(line);
bufOut.newLine();
bufOut.flush();
if("over".equals(line))
break;
String str = bufIn.readLine();
System.out.println(str);
}
s.shutdownOutpu();
bufr.close();
s.close();
}
}
class TransServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(12345); //创建一个服务端,端口号12345
Socket s = ss.accept(); //等待接受数据
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip);
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter bufOut = new BufferedWriter(new FileWriter(123.txt))); // 数据存入的地点
String line = null;
while((line=bufIn.readLine())!=null) //写入客户端发来的信息到存放的地点
{
bufOut.write(line);
bufOut.newLine();
bufOut.flush();
}
s.close();
ss.close();
}
}
作者:
郭振
时间:
2012-5-18 21:14
//TCP客户端
import java.io.*;
import java.net.*;
public class TcpSocket {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
if(args.length!=1)
{
System.out.println("请选一个文件");
return;
}
File file=new File(args[0]);
if(!file.exists()&&file.isFile())
{
System.out.println("文件不存在,或者不是文件");
}
//创建一个客户端
Socket s=new Socket("192.168.0.101",10005);
//创建字节流得到要上穿的文件
FileInputStream fin=new FileInputStream(file);
//通过OutputStream()方法返回OutputStream
OutputStream out=s.getOutputStream();
//创建一个缓冲区临时存储文件
byte []buf=new byte[1024];
int len=0;
//使用read读取文件
while((len=fin.read(buf))!=-1)
{ //把文件写到Socket流
out.write(buf,0,len);
}
//创建一个结束标记通知服务端
s.shutdownOutput();
//创建InputStream得到服务器的返回信息
InputStream in=s.getInputStream();
byte[]bufin=new byte[1024];
int num=in.read(bufin);
System.out.println(new String(bufin,0,num));
fin.close();
s.close();
}
}
//tcp服务端
import java.io.*;
import java.net.*;
public class TcpSeverSocket {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
//创建tcp服务端
ServerSocket ss=new ServerSocket(10005);
//通过循环的使用多线程方式获取客户端的上传数据
while(true){
//接受客户端数据
Socket s=ss.accept();
//创建一个线程
new Thread(new jpg(s)).start();
}
}
}
class jpg implements Runnable{
private Socket s;
jpg(Socket s)
{
this.s=s;
}
@Override
public void run() {
// TODO Auto-generated method stub
//获取客户端的ip地址
String ip=s.getInetAddress().getHostName();
//为是继承Runnable只能对try
try {
//定义一个计数器重复的文件进行命名
int count=0;
//打印ip地址
System.out.println(ip+"guozheng");
//使用getInputStream()方法获取字节流
InputStream in=s.getInputStream();
//对文件名称进行判断,如果有重名的文件文件名就自动加1
File file=new File(ip+"("+count+")"+".jpg");
if(file.exists())
file=new File(ip+"("+(count++)+")"+".jpg");
//创建FileOutputStream把客户端上传的文件写到自己要存储的地方
FileOutputStream fo=new FileOutputStream(file);
byte []buf=new byte[1024];
int len=0;
while((len=in.read(buf))!=-1)
{
fo.write(buf,0,len);
}
//客户端上文件后,给客户端反馈信息
OutputStream out=s.getOutputStream();
out.write("上传成功".getBytes());
fo.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
作者:
韩国军
时间:
2012-5-18 21:52
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class UpLoad {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(3000);
Socket socket = ss.accept();
new Thread(new Receive(socket)) {
}.start();
}
}
class Receive implements Runnable {
private Socket socket;
public Receive(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedInputStream bis = new BufferedInputStream(socket
.getInputStream());
byte[] bFileName = new byte[255];
int len = bis.read(bFileName);
String fileName = new String(bFileName, 0, len).trim();
byte[] bytes = new byte[1024];
FileOutputStream fos = new FileOutputStream("d://" + fileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
len = 0;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
bos.close();
fos.close();
bis.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.BufferedOutputStream;
public class UpLoadClient {
public static void main(String[] args) throws Exception {
BufferedReader br = null;
String path = null;
String fileName = null;
String ip = null;
while (true) {
System.out.println("请输入文件路径:");
br = new BufferedReader(new InputStreamReader(System.in));
path = br.readLine();
File file = new File(path);
fileName = path.substring(path.lastIndexOf("//") + 1);
if (file.isDirectory() || !file.exists())
System.out.println("路径不正确!");
else
break;
}
System.out.println("请输入服务器地址:");
br = new BufferedReader(new InputStreamReader(System.in));
ip = br.readLine();
System.out.println("确认上传:" + path + "文件吗(y/n)?");
br = new BufferedReader(new InputStreamReader(System.in));
String result = br.readLine();
if ("n".equalsIgnoreCase(result)) {
br.close();
return;
}
Socket socket = new Socket(ip, 3000);
FileInputStream fs = new FileInputStream(path);
byte[] bytes = new byte[1024];
BufferedOutputStream bos = new BufferedOutputStream(socket
.getOutputStream());
while (true) {
if (fileName.getBytes().length < 255)
fileName += "/u0000";
else
break;
}
bos.write(fileName.getBytes());
bos.flush();
int len = 0;
while ((len = fs.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
bos.close();
fs.close();
br.close();
socket.close();
System.out.println("文件上传完毕!");
}
}
作者:
郭凯敏
时间:
2012-7-22 04:40
本帖最后由 郭凯敏 于 2012-7-22 04:41 编辑
支持一个
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2