客户端:
public class picClient {
public static void main(String[] args) {
Socket s=null;
FileInputStream fis=null;
try {
s=new Socket("192.168.56.1",10006);
//要上传的图片
fis=new FileInputStream("e:\\aa.jpg");
//获取socket中的输出流
OutputStream os=s.getOutputStream();
byte[] buf=new byte[1024];
int len=0;
while((len=fis.read(buf))!=-1){
os.write(buf,0,len);
}
//结束标记,告诉服务端数据写完
s.shutdownOutput();
//获取读入流
InputStream is=s.getInputStream();
byte[] bufIn=new byte[1024];
int num=is.read(bufIn);
//输出服务器返回信息
System.out.println(new String(bufIn,0,num));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fis!=null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务端:
public class picServer {
public static void main(String[] args) {
ServerSocket ss=null;
Socket s=null;
FileOutputStream fos=null;
try {
ss=new ServerSocket(10006);
//获取客户端对象
s=ss.accept();
String id=s.getInetAddress().getHostAddress();
System.out.println(id+".....connected");
//创建保存文件
fos=new FileOutputStream("e:\\tom.jpg");
InputStream is=s.getInputStream();
byte[] buf=new byte[1024];
int len=0;
while((len=is.read(buf))!=-1){
fos.write(buf, 0, len);
}
//返回给客户端信息
OutputStream os=s.getOutputStream();
os.write("上传成功".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
|