14-5 网络编程 ---- TCP网络编程(2)例子2
例题2:客户端发送文件给服务端,服务端将文件保存在本地
运行步骤:
(1)启动server
(2)再启动client
(3)之后在server会显示发送来的信息
(这里的127.0.0.1为本机,即本机给本机发信息,由本机接收)
代码:
package java1;
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
//实现TCP的网络编程
//例题2:客户端发送文件给服务端,服务端将文件保存在本地。
public class TCPTest2 {
@Test
public void client(){
OutputStream os = null;
FileInputStream fis = null;
Socket socket = null;
try {
//1.造Socket
socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
//2.获取输出流
os = socket.getOutputStream();
//3.获取输入流
fis = new FileInputStream(new File("漂移火辣辣.jpg"));
//4.读取
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1){
os.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//5.关闭
if(fis != null){
try {
fis.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();
}
}
}
}
@Test
public void server(){
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
FileOutputStream fos = null;
try {
//1.造一个ServerSocket
ss = new ServerSocket(9000);
//2.获取客户端的socket
socket = ss.accept();
//3.获取客户端的输入流
is = socket.getInputStream();
//4.保存数据到本地
fos = new FileOutputStream(new File("漂移火辣辣1.jpg"));
//5.读写过程
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//6.关闭
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();
}
}
}
}
}