使用TCP网络编程进行客户端向服务器端传输文件,代码如下: 客户端: @Test public void client(){ Socket socket = null; OutputStream outputStream = null;
BufferedInputStream bufferedInputStream = null;
try {
// 根据地址获取服务端IP对象
InetAddress byName = InetAddress.getByName("127.0.0.1");
// 获取socket套接字
// IP地址 + 端口号
socket = new Socket(byName,8898);
// 获取socket的输出流
outputStream = socket.getOutputStream();
bufferedInputStream = new BufferedInputStream(new FileInputStream(new File("C:\\Users\\86133\\Desktop\\test.txt")));
int len;
byte[] bytes = new byte[1024];
while ((len = bufferedInputStream.read(bytes)) != -1) {
outputStream.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
outputStream.close();
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器端: @Test public void server(){ ServerSocket serverSocket = null; Socket socket = null; InputStream inputStream = null; BufferedOutputStream bufferedOutputStream = null; try { // 这个端口号是自己创建的server端口号, // client端正是根据这个端口号发送信息的 serverSocket = new ServerSocket(8898); socket = serverSocket.accept(); inputStream = socket.getInputStream();
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("C:\\Users\\86133\\Desktop\\test2.txt")));
int len;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1){
String s = String.valueOf(bytes);
bufferedOutputStream.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
socket.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
结果: test2.txt文件夹中没有任何信息: 对服务器端进行debug,发现一直到文件输出流写入文件部分都没有问题,写入的byte数组是有值的: 只有可能是文件关闭部分出现问题,发现输出缓冲流bufferedOutputStream未关闭!这会导致文件写入失败!!!
修改后的服务器端: @Test public void server(){ ServerSocket serverSocket = null; Socket socket = null; InputStream inputStream = null; BufferedOutputStream bufferedOutputStream = null; try { // 这个端口号是自己创建的server端口号, // client端正是根据这个端口号发送信息的 serverSocket = new ServerSocket(8898); socket = serverSocket.accept(); inputStream = socket.getInputStream();
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("C:\\Users\\86133\\Desktop\\test2.txt")));
int len;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1){
String s = String.valueOf(bytes);
bufferedOutputStream.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
serverSocket.close();
socket.close();
inputStream.close();
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果:test2.txt文件成果写入。
|