当前位置:网站首页>TCP传输
TCP传输
2022-07-25 09:27:00 【看小虫子】
服务端
package TCPUDP;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo01 {
public static void main(String[] args) throws Exception {
//1,创建一个端口
ServerSocket serverSocket = new ServerSocket(9000);
//2,监听客户端的连接
Socket socket = serverSocket.accept();//阻塞式监听,会一至等客户端连接
//3,获取输入流
InputStream is = socket.getInputStream();
//4,文件移动
FileOutputStream fos = new FileOutputStream(new File("receive"));
byte[] buffer = new byte[1024];
int len;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
//通知·客户端接收完毕
OutputStream os = socket.getOutputStream();
os.write("我接收完毕,你可以断开了".getBytes());
//关闭资源
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
客户端
有bug图片一直找不到,已经放弃,代码还可无错
package TCPUDP;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo02 {
public static void main(String[] args) throws IOException {
//1,创建一个Socket连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
//2,创建一个输出流
OutputStream os=socket.getOutputStream();
//3,文件流
FileInputStream fis = new FileInputStream(new File("fj.jpg"));
//4,写出文件
byte[] buffer = new byte[1024];
int len;
while((len=fis.read())!=-1){
os.write(buffer,0,len);
}
//通知服务器,我已经结束了
socket.shutdownOutput();//我已经传输完了
//确定服务器接收完毕,才能断开连接(字符串管道流)
InputStream inputStream=socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while((len2=inputStream.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
//关闭资源
baos.close();
inputStream.close();
fis.close();
os.close();
socket.close();
}
}
边栏推荐
- [machine translation] scones -- machine translation with multi tag tasks
- DHCP的配置(以华为eNSP为例)
- 多线程——死锁和synchronized
- JDBC操作数据库详解
- Leetcode 560 前缀和+哈希表
- Is binary cross entropy really suitable for multi label classification?
- UE4 窗口控制(最大化 最小化)
- message from server: “Host ‘xxx.xxx.xxx.xxx‘ is not allowed to connect to this MySQL server“
- Common methods of JS digital thousand bit segmentation
- Probabilistic robot learning notes Chapter 2
猜你喜欢
随机推荐
Wechat applet jumps to other applets
链表相关(设计链表及环链表问题)
T5 paper summary
File upload function
js加密参数定位
oh-my-zsh和tmux配置(个人)
广度优先遍历(图和二叉树的层序遍历相关问题)
静态路由的配置(以华为eNSP为例)
Nodejs初体验
腾讯云之错误[100007] this env is not enable anonymous login
21. Merge Two Sorted Lists
GUI窗口
UE4 快速找到打包失败的原因
The way of code neatness -- hit the pain point directly
Summary of most consistency problems
vscode插件开发
pnpm简述
@Import, conditional and @importresource annotations
鼠标监听,画笔
Detailed explanation of JDBC operation database





![腾讯云之错误[100007] this env is not enable anonymous login](/img/a2/a209a0d94e3fbf607242c28d87e2dd.png)
![[necessary for growth] Why do I recommend you to write a blog? May you be what you want to be in years to come.](/img/f5/e6739083f0dce8da1d09d078321633.png)


