public class TCPTest3 {
/*
这里涉及到的异常,应该使用try-catch-finally处理
*/
@Test
public void client() throws IOException {
//1.创建Socket对象,指明服务器端的ip和端口号
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
//2.获取一个输出流,用于输出数据
OutputStream os = socket.getOutputStream();
//3.造读取文件的输入流
//可以是一句话 客户端发送信息一句话给服务端,服务端将数据显示在控制台上
// os.write("你好,我是客户端mm".getBytes());
FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
//4.数据的输出过程
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1){
os.write(buffer,0,len);
}
//关闭数据的输出
socket.shutdownOutput();
//5.接收来自于服务器端的数据,并显示到控制台上
InputStream is = socket.getInputStream();
//不建议这样读取,可能会有乱码
// byte[] buffer = new byte[1024];
// int len;
// while((len = is.read(buffer)) != -1){
// String str = new String(buffer,0,len);
// System.out.print(str);
// }
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bufferr = new byte[20];
int len1;
while((len1 = is.read(buffer)) != -1){
baos.write(bufferr,0,len1);
}
System.out.println(baos.toString());
//6.
fis.close();
os.close();
socket.close();
baos.close();
}
/*
这里涉及到的异常,应该使用try-catch-finally处理
*/
@Test
public void server() throws IOException {
//1.创建服务器端的ServerSocket,指明自己的端口号
ServerSocket ss = new ServerSocket(9090);
//2.调用accept()表示接收来自于客户端的socket
Socket socket = ss.accept();
//3.获取输入流
InputStream is = socket.getInputStream();
//4.读取并保存输入流中的数据
FileOutputStream fos = new FileOutputStream(new File("beauty2.jpg"));
//5.
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
System.out.println("图片传输完成");
//6.服务器端给予客户端反馈
OutputStream os = socket.getOutputStream();
os.write("你好,照片我已收到,非常美!".getBytes());
//7.
fos.close();
is.close();
socket.close();
ss.close();
os.close();
}
}