Socket连续读取两次数据

版权声明:1184905186 风里雨里qq等你^_^!! https://blog.csdn.net/hello_word2/article/details/82228631

实现功能:客户端上传一张图片交给服务端后再次上传一句话告诉服务端已经上传完毕;

服务端代码:

package com.fpy.socket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	public static void main(String[] args) throws Exception {
		System.out.println("----------------------Server------------------");
		ServerSocket server = new ServerSocket(8888);
		Socket socket = server.accept();
		BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\1.jpg"));
		
		byte[] b = new byte[1024];
		int len = 0;
		while((len=bis.read(b)) !=-1){
			bos.write(b, 0, len);
			//循环读取数据会造成流的堵塞 当数据读取完毕后手动结束循环
			if(len!=b.length){
				break ;
			}
		}
		bos.flush();
		System.out.println("接收第二条信息");
		DataInputStream dis = new DataInputStream(socket.getInputStream());
		String mess = dis.readUTF();
		System.out.println(mess);

		bos.close();
		server.close();
	}
}

客户端代码:

package com.fpy.socket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class Client {
	public static void main(String[] args) throws Exception, IOException {
		System.out.println("---------------------client-------------------");
		Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
		BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\2.jpg"));
		
		byte[] b = new byte[1024];
		int len = 0;
		while((len = bis.read(b))!=-1){
			bos.write(b, 0, len);
			//(221,184 
			// 224,839 字节
		}
		bos.flush();
		System.out.println("第二次传输数据");
		DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
		dos.writeUTF("上传完毕");
		dos.flush();
		
		dos.flush();
		
	}
}

 

展开阅读全文

没有更多推荐了,返回首页