package lianxi;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class work5Fuwu {
/**
* 使用socket编写一个Java程序,要求:客户端上传图片到服务端,服务端接收完毕后存放到本地,
* 并发送“接收完毕”的信息到客户端,客户端在控制台显示接收的情况
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket socket=new ServerSocket(45454);
System.out.println("等待客户端连接......");
Socket so=socket.accept();//创建通道
InetAddress intetAddress=so.getInetAddress();//连接的客户端地址
System.out.println("连接的客户端地址:"+intetAddress.getHostAddress());//打印地址
InputStream in=so.getInputStream();//创建输入流准备接受数据
FileOutputStream fos=new FileOutputStream("p3.ico");
int len=0;
byte[] b=new byte[1024];
while((len=in.read(b))!=-1){//读取传来的数据
fos.write(b);
}
so.shutdownInput();
OutputStream out=so.getOutputStream();//创建输出流
//FileWriter out=so.FileWriter();
out.write("服务器发送的接收完毕了".getBytes());//传出数据
//
out.close();//关闭流
fos.close();
in.close();
}
}
package lianxi;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class work5KeHu {
/**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
//++++++++++++++客户端++++++++++++++++++++++++
Socket socket =new Socket("192.168.0.108", 45454);
System.out.println("以连接到服务器端");
OutputStream out=socket.getOutputStream();//输出流
FileInputStream fin=new FileInputStream("panda.ico");//从本地获取图片
int len=0;
byte[]bytes=new byte[1024];
while((len=fin.read(bytes))!=-1){//读取图片
out.write(bytes, 0, len);//传到服务器
}
socket.shutdownOutput();
InputStream in=socket.getInputStream();//准备接收数据
InputStreamReader isr=new InputStreamReader(in);
char[] chars=new char[1024];
len=0;
while((len=isr.read(chars))!=-1){//接收数据
System.out.println(new String(chars,0,len));
}
in.close();
fin.close();
out.close();
}
}
|
|