@Test
public void testServer() {
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
BufferedOutputStream bos = null;
try {
//1.获取服务端 serverSocket ,指明端口号
ss = new ServerSocket(9090);
//2.获取客户端socket
socket = ss.accept();
//3.获取输入流
is = socket.getInputStream();
//4.数据操作
File file = new File("src\\Day4_14\\老鹰copy.webp");
//File file = new File("src\\Day4_14\\helloCopy.txt");
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
String str = new String(buffer, 0, len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//5.关流
if (bos!=null) {
try {
bos.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();
}
}
}
}
@Test 客户端
public void testClent() {
Socket socket = null;
OutputStream os = null;
BufferedInputStream bis = null;
try {
//1.创建socket ,指明Ip 端口号
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet, 9090);
//2.获取输出流
os = socket.getOutputStream();
//3.写出数据
// File file = new File("src\\Day4_14\\hello.txt");
File file = new File("src\\Day4_14\\老鹰.webp");
FileInputStream fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
os.write(buffer, 0, len);
String str = new String(buffer, 0, len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关流
if (bis!=null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os!=null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket!=null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}