TCP协议接收数据的步骤:
A:创建接收数据的Socket对象
创建对象的时候要指定端口
B:监听客户端连接
等待客户端连接
C:获取Socket对象的输入流(字节流)
D:读数据,并显示在控制台
E:释放资源
服务器:
public class FileServerDemo {
public static void main(String[] args) throws IOException {
//创建服务器对象
ServerSocket ss = new ServerSocket(8080);
//监听客户端连接
Socket s = ss.accept();
//包装通道内的输入流
BufferedInputStream bis = new BufferedInputStream(
s.getInputStream());
//把数据写入文件
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("C:\\Users\\MA\\Desktop\\IOtest\\copy.jpg"));
byte[] bys = new byte[1024];
int len = 0;
while((len = bis.read(bys))!=-1){
bos.write(bys,0,len);
}
//把通道内的输出流包装
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
write.write("文件上传成功");
write.newLine();
write.flush();
//释放资源
bos.close();
s.close();
ss.close();
}
}
TCP协议发送数据的步骤:
A:创建发送数据的Socket对象
创建对象的时候要指定主机和端口
B:获取Socket对象的输出流(字节流)
C:写数据
D:释放资源
客户端:
public class FileClientDemo {
public static void main(String[] args) throws IOException {
//创建客户端对象
Socket s = new Socket("172.24.60.182",8080);
//读取文件的数据
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\MA\\Desktop\\电路指导书\\QQ图片20180627212519.jpg"));
//把通道内的输出流包装
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
byte[] bys = new byte[1024];
int len = 0;
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
//给服务器一个反馈
s.shutdownOutput();//禁用输出流
//获取服务器的反馈信息
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String data = reader.readLine();
System.out.println("client:"+data);
bis.close();
s.close();
}
}
来源:https://www.cnblogs.com/mxj961116/p/9348732.html