0
点赞
收藏
分享

微信扫一扫

Socket ----TCP---实现文件的复制


TCP

1.特点

1.底层基于流模式实现,通过三次握手(成功)建立连接,比UDP可靠,但是传输的速度慢
2.TCP是通过字节流的形式直接传输数据,所以不用限制大小
3.传输文件全,不回丢失信息,一般用在文件的传输
4.实现: 客户端(Socket) 服务端(ServerSocket)

原理图

Socket ----TCP---实现文件的复制_客户端


tcp的三次握手

2. 代码实现:

客户端:

public class TCPClienDemo {
public static void main(String[] args) throws Exception {
// 创建套接字对象
Socket sc = new Socket("127.0.0.1",3366);
// 获取自带的流信息
OutputStream os = sc.getOutputStream();
// 写数据
os.write("你好,服务器,我是客户端".getBytes());
// 告知服务器写完了
sc.shutdownOutput();
// 关流
os.close();
}
}

服务器端:

public class TCPServerDemo {
public static void main(String[] args) throws Exception {
//获取套接子
ServerSocket ss = new ServerSocket(3366);
//接受客户端发来的请求
Socket scoket = ss.accept();
//获取自带的流信息
InputStream is = scoket.getInputStream();
//缓冲区
byte[] by = new byte[1024];
int len = -1;
while((len = is.read(by))!=-1) {
System.out.println(new String(by,0,len));
}
//通知客户端接受完成
scoket.shutdownInput();
//关闭流
is.close();
}
}

  • 记住先启动服务器端,在启动客户端

3. 实现文件的复制

客户端:

/*
* 客户端
*/
public class TCPCopyFileClien{
public static void main(String[] args) throws Exception {
// 获取socket
Socket s = new Socket();
// 发起连接
s.connect(new InetSocketAddress("127.0.0.1",3309));
OutputStream ops = s.getOutputStream();
// 读取文件
FileInputStream fis = new FileInputStream(new File("/home/luodong/文档/a/e.txt"));
int len = -1;
byte[] by = new byte[1024];
while((len = fis.read(by))!=-1) {
// 写入服务器
ops.write(by);
}
s.shutdownOutput();
// 写入客户端
ops.close();
fis.close();
}
}

服务器端:

/*
* 服务器端
*/
public class TCPCopyFileServer {
public static void main(String[] args) throws Exception {
// 获取连接
ServerSocket ss = new ServerSocket(3309);
//接受客户端发来的请求
Socket s = ss.accept();
// 获取流行西
InputStream is = s.getInputStream();
// 输出流
FileOutputStream fos = new FileOutputStream(new File("/home/luodong/文档/a/ee.txt"));
int len = -1;
byte[] by = new byte[1024];
while((len = is.read(by))!=-1) {
fos.write(by);
}
s.shutdownInput();
is.close();
fos.close();

}
}


举报

相关推荐

0 条评论