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

来源:互联网 发布:怎么用手机做淘宝客服 编辑:程序博客网 时间:2024/05/22 10:24

客户端:

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 0
原创粉丝点击