使用TCP从客户端上传图片到服务器端

客户端:

package upload.tcp;


import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import java.net.Socket;
import java.net.UnknownHostException;


/*
 * 从客户端上传图片到服务器端
 */
public class TCPClient {


/**
* @param args
* @throws IOException 
* @throws UnknownHostException 
*/
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
//1.创建客户端Socket对象
Socket s=new Socket("192.168.166.193",10008);

//2.读取要上传的图片。源:硬盘。
InputStream is=new FileInputStream("d://dog.jpg");

//3.将图片发送到服务器端。目的:Socket流
OutputStream out=s.getOutputStream();
byte [] bt=new byte[1024];
int len=0;
while((len=is.read(bt))!=-1)
{
out.write(bt,0,len);
}
s.shutdownOutput();

//4.接收服务器端返回的数据。源:Socket流
InputStream isIn=s.getInputStream();
byte [] btIn=new byte[1024];
int lenIn=isIn.read(btIn);
String text=new String(btIn,0,lenIn);
System.out.println(text);

//告诉服务器端,上传结束


//关闭资源
is.close();
s.close();

}


}


服务器端:

package upload.tcp;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;


public class TCPServer {


/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//1.创建服务器端的ServerSocket对象
ServerSocket ss=new ServerSocket(10008);

//2.获取Socket对象
Socket s=ss.accept();
String ip=s.getInetAddress().getHostAddress();
System.out.println(ip+"connected...");
//3.接收客户端传来的图片。源:Socket流
InputStream in=s.getInputStream();

//4.存放到服务器端的硬盘。目的:硬盘
File dir=new File("d:\\pic");
if(!dir.exists()) dir.mkdirs();
File file=new File(dir,ip+".jpg");
FileOutputStream os=new FileOutputStream(file);
byte [] bt=new byte[1024];
int len;
while((len=in.read(bt))!=-1)
{
os.write(bt, 0, len);
}

//5.告诉客户端上传成功。目的:Socket流
OutputStream out=s.getOutputStream();
out.write("上传成功".getBytes());


//关闭资源
in.close();
s.close();
ss.close();

}


}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值