实现将客户端的1.jpg,发送到服务器端的4.jpg中。
接受成功后服务器端会发送一个反馈信息给客户端
客户端把信息在显示台中显示出来。
@Test
public void testClient() {
//客户端
Socket socketClient = null;
OutputStream os = null;
FileInputStream fis = null;
InputStream is = null;
try {
//1,创建Socket对象,指明服务器端的IP地址和端口号
InetAddress inet = InetAddress.getByName("127.0.0.1");
socketClient = new Socket(inet, 8899);
//2,获取一个输出流,用于输出数据
os = socketClient.getOutputStream();
// os.write("好好学习,天天向上".getBytes());
//3,写出数据的操作
fis = new FileInputStream(new File("1.jpg"));
int len;
byte[] buff = new byte[1024];
while ((len = fis.read(buff)) != -1) {
os.write(buff,0,len);
}
//4,接受来自于服务器端的反馈数据,并显示在控制台上
socketClient.shutdownOutput();//要关闭对应的输出流,表示数据传送完毕,同时通知服务器端
is = socketClient.getInputStream();
int lenback;
byte[] backBuff = new byte[1024];
while ((lenback = is.read(backBuff)) != -1) {
String str = new String(backBuff,0,lenback);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//5,流的关闭
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socketClient != null) {
try {
socketClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void testServer() {
//服务器端
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
OutputStream os = null;
try {
//1,创建服务器端的ServerSocket,指明自己的端口号
ss = new ServerSocket(8899);
//2,调用accept()方法表示接受来自于客户端的Socket
socket = ss.accept();
//3,获取输入流
is = socket.getInputStream();
fos = new FileOutputStream(new File("4.jpg"));
//4,读取输入流中的数据
byte[] buff = new byte[1024];
int len;
while ((len = is.read(buff)) != -1) {
// String str = new String(buff, 0, len);
// System.out.print(str);
fos.write(buff,0,len);
}
//服务器端需要得到一个指示,表示客户端不再发送数据了
//因此需要在客户端中显示调用对应的数据关闭操作,因为read方法是阻塞方法
System.out.println("接收到了"+socket.getInetAddress().getHostAddress()+"发送过来的数据,并且已经发送反馈数据");
//5,服务器端给予客户端反馈,表示已经接受到了发送过来的数据
os = socket.getOutputStream();
os.write("图片我已收到,非常不错".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//6,流的关闭
if(os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}